package com.xbongbong.paas.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.data.service.CabinetFileService;
import com.xbongbong.paas.data.service.RichTextService;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasFormEntity;
import com.xbongbong.paas.domain.entity.PaasProcessDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.PaySheetTypeEnum;
import com.xbongbong.paas.enums.PaymentSheetTypeEnum;
import com.xbongbong.paas.enums.SheetTypeEnum;
import com.xbongbong.paas.help.FormDataValidateProductHelp;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.pojo.AddMuchFieldPojo;
import com.xbongbong.paas.pojo.AssociatedBusinessAfterSavePojo;
import com.xbongbong.paas.pojo.dto.FormDataAddDTO;
import com.xbongbong.paas.pojo.dto.FormDataUpdateDTO;
import com.xbongbong.paas.pojo.dto.SaasFormSaveDTO;
import com.xbongbong.paas.pojo.dto.ValidateDataDTO;
import com.xbongbong.paas.pojo.vo.AfterSaveVO;
import com.xbongbong.paas.pojo.vo.FormDataAddVO;
import com.xbongbong.paas.service.PaasFormDataService;
import com.xbongbong.paas.service.ProModelService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.Arith;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.JsonHelperUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.domain.entity.ReRollBackEntity;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.PackageStatusEnum;
import com.xbongbong.pro.enums.RichTextEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.ValueAddedTypeEnum;
import com.xbongbong.pro.enums.errorcodes.BuinessDefaultErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.TemplateErrorCodeEnum;
import com.xbongbong.pro.formdata.pojo.SaasNeedRedundantAttrPojo;
import com.xbongbong.pro.formdata.pojo.vo.BeforeSaveVO;
import com.xbongbong.pro.formdata.pojo.vo.SaveVO;
import com.xbongbong.pro.log.pojo.DetailLogPojo;
import com.xbongbong.pro.message.pojo.dto.ConsistencySyncRabbitMqDTO;
import com.xbongbong.pro.payment.pojo.dto.PaymentDTO;
import com.xbongbong.pro.paymentsheet.pojo.dto.batch.PaymentSheetDTO;
import com.xbongbong.pro.paymentsheet.pojo.vo.batch.PaymentSheetAmountVO;
import com.xbongbong.pro.payplan.pojo.dto.PayPlanDTO;
import com.xbongbong.pro.payplansheet.pojo.dto.batch.PayPlanSheetDTO;
import com.xbongbong.pro.payplansheet.pojo.vo.batch.PayPlanSheetAmountVO;
import com.xbongbong.pro.rabbitmq.producer.ConsistencySyncProducer;
import com.xbongbong.pro.service.toolbox.elasticsearch.help.ProEsHelper;
import com.xbongbong.pro.thread.ThreadPoolBeanConfig;
import com.xbongbong.process.operate.ProcessStartHelp;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ErrorMessageConstant;
import com.xbongbong.saas.domain.entity.ContractPerformanceEntity;
import com.xbongbong.saas.domain.entity.OnlinePaymentFlowEntity;
import com.xbongbong.saas.domain.entity.WorkOrderEntity;
import com.xbongbong.saas.domain.entity.competitor.CompetitorEntity;
import com.xbongbong.saas.domain.entity.ext.AssembleEntityExt;
import com.xbongbong.saas.domain.entity.ext.BomBillEntityExt;
import com.xbongbong.saas.domain.entity.ext.ContactEntityExt;
import com.xbongbong.saas.domain.entity.ext.ContractEntityExt;
import com.xbongbong.saas.domain.entity.ext.CreditFixedLimitEntityExt;
import com.xbongbong.saas.domain.entity.ext.CreditLimitEntityExt;
import com.xbongbong.saas.domain.entity.ext.CreditTemporaryLimitEntityExt;
import com.xbongbong.saas.domain.entity.ext.CustomerCommunicateEntityExt;
import com.xbongbong.saas.domain.entity.ext.CustomerEntityExt;
import com.xbongbong.saas.domain.entity.ext.InstockEntityExt;
import com.xbongbong.saas.domain.entity.ext.InventoryEntityExt;
import com.xbongbong.saas.domain.entity.ext.InvoiceEntityExt;
import com.xbongbong.saas.domain.entity.ext.OpportunityEntityExt;
import com.xbongbong.saas.domain.entity.ext.OutstockEntityExt;
import com.xbongbong.saas.domain.entity.ext.PayPlanEntityExt;
import com.xbongbong.saas.domain.entity.ext.PayPlanSheetEntityExt;
import com.xbongbong.saas.domain.entity.ext.PaymentEntityExt;
import com.xbongbong.saas.domain.entity.ext.PaymentSheetEntityExt;
import com.xbongbong.saas.domain.entity.ext.PaymentTaskEntityExt;
import com.xbongbong.saas.domain.entity.ext.ProductionOrderEntityExt;
import com.xbongbong.saas.domain.entity.ext.PurchaseEntityExt;
import com.xbongbong.saas.domain.entity.ext.PurchaseInvoiceEntityExt;
import com.xbongbong.saas.domain.entity.ext.QuotationEntityExt;
import com.xbongbong.saas.domain.entity.ext.RefundEntityExt;
import com.xbongbong.saas.domain.entity.ext.ReturnedPurchaseEntityExt;
import com.xbongbong.saas.domain.entity.ext.SupplierContactEntityExt;
import com.xbongbong.saas.domain.entity.ext.SupplierEntityExt;
import com.xbongbong.saas.domain.entity.ext.TransferEntityExt;
import com.xbongbong.saas.enums.InstockTypeEnum;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.OrderOutStockExpressStatusEnum;
import com.xbongbong.saas.enums.PaymentLinkTypeEnum;
import com.xbongbong.saas.enums.RedundantTemplateTypeEnum;
import com.xbongbong.saas.enums.SheetAloneEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.base.PaymentBaseEnum;
import com.xbongbong.saas.enums.business.*;
import com.xbongbong.saas.enums.dictionary.PayPlanStatusEnum;
import com.xbongbong.saas.enums.dictionary.PaymentStatusEnum;
import com.xbongbong.saas.enums.dictionary.PublicEnum;
import com.xbongbong.saas.enums.dictionary.WarehouseOriStockEnum;
import com.xbongbong.saas.help.FundHelp;
import com.xbongbong.saas.help.InvoiceCommonHelper;
import com.xbongbong.saas.help.SaasDataInitHelp;
import com.xbongbong.saas.help.SaasSaveHelp;
import com.xbongbong.saas.help.SaasUpdateHelp;
import com.xbongbong.saas.model.AssembleModel;
import com.xbongbong.saas.model.BomBillModel;
import com.xbongbong.saas.model.ContactModel;
import com.xbongbong.saas.model.ContractModel;
import com.xbongbong.saas.model.ContractPerformanceModel;
import com.xbongbong.saas.model.CreditFixedLimitModel;
import com.xbongbong.saas.model.CreditLimitModel;
import com.xbongbong.saas.model.CreditTemporaryLimitModel;
import com.xbongbong.saas.model.CustomerCommunicateModel;
import com.xbongbong.saas.model.CustomerModel;
import com.xbongbong.saas.model.InstockModel;
import com.xbongbong.saas.model.InventoryModel;
import com.xbongbong.saas.model.InvoiceModel;
import com.xbongbong.saas.model.OnlinePaymentFlowModel;
import com.xbongbong.saas.model.OpportunityModel;
import com.xbongbong.saas.model.OutstockModel;
import com.xbongbong.saas.model.PaasFormDataModel;
import com.xbongbong.saas.model.PayPlanModel;
import com.xbongbong.saas.model.PayPlanSheetModel;
import com.xbongbong.saas.model.PaymentModel;
import com.xbongbong.saas.model.PaymentSheetModel;
import com.xbongbong.saas.model.PaymentTaskModel;
import com.xbongbong.saas.model.ProductionOrderModel;
import com.xbongbong.saas.model.PurchaseInvoiceModel;
import com.xbongbong.saas.model.PurchaseModel;
import com.xbongbong.saas.model.QuotationModel;
import com.xbongbong.saas.model.RefundModel;
import com.xbongbong.saas.model.ReturnedPurchaseModel;
import com.xbongbong.saas.model.SupplierContactModel;
import com.xbongbong.saas.model.SupplierModel;
import com.xbongbong.saas.model.TransferModel;
import com.xbongbong.saas.model.WorkOrderModel;
import com.xbongbong.saas.service.ContractService;
import com.xbongbong.saas.service.CreditFixedLimitService;
import com.xbongbong.saas.service.CreditLimitService;
import com.xbongbong.saas.service.CreditTemporaryLimitService;
import com.xbongbong.saas.service.CustomerCommunicateService;
import com.xbongbong.saas.service.DistributorAccountService;
import com.xbongbong.saas.service.DistributorCommunicateService;
import com.xbongbong.saas.service.DistributorContactService;
import com.xbongbong.saas.service.DistributorFormDataService;
import com.xbongbong.saas.service.DistributorManageService;
import com.xbongbong.saas.service.FundSetService;
import com.xbongbong.saas.service.InstockService;
import com.xbongbong.saas.service.InvoiceService;
import com.xbongbong.saas.service.OrderOutstockService;
import com.xbongbong.saas.service.OrderService;
import com.xbongbong.saas.service.PayPlanService;
import com.xbongbong.saas.service.PayPlanSheetService;
import com.xbongbong.saas.service.PaymentService;
import com.xbongbong.saas.service.PaymentSheetService;
import com.xbongbong.saas.service.PaymentTaskService;
import com.xbongbong.saas.service.PurchaseService;
import com.xbongbong.saas.service.RefundService;
import com.xbongbong.saas.service.ReturnService;
import com.xbongbong.saas.service.UserTeamService;
import com.xbongbong.saas.service.WorkOrderProductService;
import com.xbongbong.saas.service.WorkOrderService;
import com.xbongbong.saas.service.toolbox.help.LogHelp;
import com.xbongbong.saas.service.toolbox.help.PackageStatusHelp;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.UserModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * model操作工厂
 * 创建时间： 2019/1/10 16:46
 * 修改时间： 2019/1/10 16:46 梁鲁江
 *
 * @author 梁鲁江
 */
@Service("distributorProModelService")
public class DistributorProModelServiceImpl implements ProModelService {

    private static final Logger LOG = LoggerFactory.getLogger(DistributorProModelServiceImpl.class);

    @Resource
    private PaasFormDataModel paasFormDataModel;
    @Resource
    private CustomerModel customerModel;
    @Resource
    private DistributorManageService distributorManageService;
    @Resource
    private DistributorContactService distributorContactService;
    @Resource
    private OutstockModel outstockModel;
    @Resource
    private OpportunityModel opportunityModel;
    @Resource
    private BomBillModel bomBillModel;
    @Resource
    private ContractModel contractModel;
    @Resource
    private ContractService contractService;
    @Resource
    private ContactModel contactModel;
    @Resource
    private CustomerCommunicateModel customerCommunicateModel;
    @Resource
    @Lazy
    private CustomerCommunicateService customerCommunicateService;
    @Resource
    private ReturnedPurchaseModel returnedPurchaseModel;
    @Resource
    private SupplierModel supplierModel;
    @Resource
    private SupplierContactModel supplierContactModel;
    @Resource
    private PurchaseModel purchaseModel;
    @Resource
    private PurchaseService purchaseService;
    @Resource
    private PaymentModel paymentModel;
    @Resource
    private InvoiceModel invoiceModel;
    @Resource
    private PayPlanModel payPlanModel;
    @Resource
    private ProductionOrderModel productionOrderModel;
    @Resource
    private PaymentService paymentService;
    @Resource
    private InvoiceService invoiceService;
    @Resource
    private PayPlanService payPlanService;
    @Resource
    private InventoryModel inventoryModel;
    @Resource
    private TransferModel transferModel;
    @Resource
    private SaasUpdateHelp saasUpdateHelp;
    @Resource
    private SaasSaveHelp saasSaveHelp;
    @Resource
    private AssembleModel assembleModel;
    @Resource
    private PaasFormDataService paasFormDataService;
    @Resource
    private InstockModel instockModel;
    @Resource
    private InstockService instockService;
    @Resource
    private RefundService refundService;
    @Resource
    private RefundModel refundModel;
    @Resource
    private WorkOrderModel workOrderModel;
    @Resource
    private WorkOrderService workOrderService;
    @Resource
    private ProEsHelper proEsHelper;
    @Resource
    private ConsistencySyncProducer consistencySyncProducer;
    @Resource
    private CabinetFileService cabinetFileService;
    @Resource
    private MongoLogHelp mongoLogHelp;
    @Resource
    private LogHelp logHelp;
    @Resource
    private ThreadPoolBeanConfig threadPoolBeanConfig;
    @Resource
    private WorkOrderProductService workOrderProductService;
    @Resource
    private ContractPerformanceModel contractPerformanceModel;
    @Resource
    private UserModel userModel;
    @Resource
    private QuotationModel quotationModel;
    @Resource
    private PaymentSheetService paymentSheetService;
    @Resource
    private PaymentSheetModel paymentSheetModel;
    @Resource
    private UserTeamService userTeamService;
    @Resource
    private FormDataValidateProductHelp formDataValidateProductHelp;
    @Resource
    private PayPlanSheetService payPlanSheetService;
    @Resource
    private FundHelp fundHelp;
    @Resource
    private PayPlanSheetModel payPlanSheetModel;
    @Resource
    private PurchaseInvoiceModel purchaseInvoiceModel;
    @Resource
    private InvoiceCommonHelper invoiceCommonHelper;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private ProcessStartHelp processStartHelp;
    @Resource
    private PaymentTaskModel paymentTaskModel;
    @Resource
    private PaymentTaskService paymentTaskService;
    @Resource
    private FundSetService fundSetService;
    @Resource
    private PackageStatusHelp packageStatusHelp;
    @Resource
    private DistributorAccountService distributorAccountService;
    @Resource
    private OrderService orderService;
    @Resource
    private DistributorCommunicateService distributorCommunicateService;
    @Resource
    private DistributorFormDataService distributorFormDataService;
    @Resource
    private CreditLimitService creditLimitService;
    @Resource
    private CreditLimitModel creditLimitModel;
    @Resource
    private CreditFixedLimitService creditFixedLimitService;
    @Resource
    private CreditFixedLimitModel creditFixedLimitModel;
    @Resource
    private CreditTemporaryLimitService creditTemporaryLimitService;
    @Resource
    private CreditTemporaryLimitModel creditTemporaryLimitModel;
    @Resource
    private ReturnService returnService;
    @Resource
    private OrderOutstockService orderOutstockService;
    @Resource
    private OnlinePaymentFlowModel onlinePaymentFlowModel;
    @Resource
    private PaymentSheetFormDataServiceImpl paymentSheetFormDataService;
    @Resource
    private PaySheetFormDataServiceImpl paySheetFormDataService;
    @Resource
    private RichTextService richTextService;

    @Override
    public AfterSaveVO insert(FormDataAddDTO formDataAddDTO, PaasFormDataEntity paasFormDataEntity, PaasFormEntityExt paasFormEntityExt) throws XbbException {
        AfterSaveVO afterSaveVO = new AfterSaveVO();
        Long dataId = 0L;
        String corpid = formDataAddDTO.getCorpid();
        Integer saasMark = formDataAddDTO.getSaasMark();
        Integer businessType = formDataAddDTO.getBusinessType();
        String userId = formDataAddDTO.getUserId();
        String creatorId = paasFormDataEntity.getCreatorId();
        String creatName = "";
        if(creatorId != null){
            // 走审批时获取创建人id
            UserEntity user = userModel.getByKeyIngoreDel(creatorId, corpid);
            if (Objects.nonNull(user)){
                creatName = user.getName();
            }
        }
        OperateTypeEnum operateTypeEnum = OperateTypeEnum.NEW;
        // if (Objects.equals(1, formDataAddDTO.getIsBusinessRule())) {
        //     operateTypeEnum = OperateTypeEnum.RULE_NEW;
        // }
        String userName = Objects.equals(paasFormDataEntity.getFlowStatus(), 2) ? creatName : formDataAddDTO.getLoginUserName();
        // if (Objects.equals(userId, PaasConstant.OUT_LINK_USER_ID)) {
        //     // 外链新增的，人员叫外部人员
        //     userName = PaasConstant.OUT_LINK_USER_NAME;
        // }
        userId = Objects.equals(paasFormDataEntity.getFlowStatus(), 2) ? creatorId : userId;
        boolean isImport = Objects.equals(1, formDataAddDTO.getIsImport());
        JSONObject data = paasFormDataEntity.getData();
        //回款单or付款单标记
        boolean sheetFlag = false;
        //兼容审批移除上一步data放入的 ownerId, coUserId
        paasFormDataEntity.getData().remove(FieldTypeEnum.OWNERID.getAlias());
        paasFormDataEntity.getData().remove(FieldTypeEnum.COUSERID.getAlias());
        paasFormDataEntity.getData().remove(FieldTypeEnum.SERIALNO.getAlias());
        //移除富文本数据
        Object richTextData = paasFormDataEntity.getData().remove(RichTextEnum.RICH_TEXT.getAttr());
        ReRollBackEntity reRollBackEntity = new ReRollBackEntity();
        try {

            if (businessType == null || businessType == 0) {
                LOG.error("businessType为空");
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }
            String logName = null;
            String memo;
            String serialNo = paasFormDataEntity.getSerialNo();
            String name;
            StringBuilder sb = new StringBuilder();

            List<ValidateDataDTO> needAddValidateDataDTO = null;
            SaasFormSaveDTO saasFormSaveDTO = new SaasFormSaveDTO();
            BeanUtil.copyProperties(formDataAddDTO, saasFormSaveDTO);
            XbbRefTypeEnum  xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
            SaasNeedRedundantAttrPojo saasNeedRedundantAttrPoJo;
            FormDataAddVO formDataAddVO = new FormDataAddVO();
            switch (xbbRefTypeEnum) {
                case CUSTOMER_MANAGEMENT:
                    data.remove(DistributorEnum.ADD_CONTACT.getAttr());
                    // data.remove(DistributorEnum.CREATOR_ID.getAttr());
                    paasFormDataEntity.setData(data);
                    CustomerEntityExt customerEntityExt = new CustomerEntityExt();
                    BeanUtil.copyProperties(paasFormDataEntity, customerEntityExt);
                    customerModel.insert(customerEntityExt);
                    dataId = customerEntityExt.getId();
                    paasFormDataEntity.setId(dataId);
                    packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                    distributorManageService.afterSave(saasFormSaveDTO);
                    saasNeedRedundantAttrPoJo = formDataAddDTO.getSaasNeedRedundantAttrPoJo();
                    if (saasNeedRedundantAttrPoJo != null) {
                        needAddValidateDataDTO = saasNeedRedundantAttrPoJo.getNeedAddValidateDataDTO();
                        if (!Objects.isNull(needAddValidateDataDTO)) {
                            // TODO 审批过来的数据是最后审批人的userId
                            for (ValidateDataDTO validateDataDTO : needAddValidateDataDTO) {
                                validateDataDTO.setProcessCreatorId(paasFormDataEntity.getCreatorId());
                            }
                            distributorFormDataService.batchAddContact(needAddValidateDataDTO, customerEntityExt.getId(), formDataAddDTO.getLoginUser(), DistributorContactEnum.DISTRIBUTOR_NAME.getAttr(), XbbRefTypeEnum.CONTACT);
                        }
                    }
                    // 记录日志(有名称的格式为编号(名称)，无名称的格式为编号)
                    if(!isImport){
                        logName = FastJsonHelper.getStringOrDefaultFromFormData(data, DistributorEnum.NAME.getAttr(), "");
                        memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, XbbRefTypeEnum.DISTRIBUTOR_MANAGEMENT.getName(), logName);
                        mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.DISTRIBUTOR, operateTypeEnum,
                                paasFormDataEntity.getId().toString(), logName, memo, formDataAddDTO.getHttpHeader());
                    }
                    break;
                case CONTRACT:
                    data = paasFormDataEntity.getData();
                    data.remove(ContractEnum.ADD_PAYMENT.getAttr());
                    JSONArray productArray = saasSaveHelp.formatSelectProduct4Save2(data, ContractEnum.PRODUCT.getAttr());
                    data.remove(ContractEnum.ADD_PAYMENT_SHEET.getAttr());
                    data.remove(ContractEnum.ADD_WRITE_OFF_PREPAYMENT.getAttr());
                    // 添加已出库优惠金额字段以及默认值
                    data.put(OrderEnum.OUTSTOCK_DISCOUNT_AMOUNT.getAttr(), 0);
                    paasFormDataEntity.setData(data);
                    ContractEntityExt contractEntityExt = new ContractEntityExt();
                    BeanUtil.copyProperties(paasFormDataEntity, contractEntityExt);
                    // 关联产品特殊处理
                    /*JSONObject conProductDataList =contractEntityExt.getData();
                    saasSaveHelp.formatSelectProduct4Save(conProductDataList, ContractEnum.PRODUCT.getAttr());
                    contractEntityExt.setData(conProductDataList);*/
                    contractModel.insert(contractEntityExt);
                    // 保存合同后的操作
                    dataId = contractEntityExt.getId();
                    paasFormDataEntity.setAddTime(contractEntityExt.getAddTime());
                    paasFormDataEntity.setId(dataId);
                    paasFormDataEntity.getData().put(ContractEnum.PRODUCT.getAttr(),productArray);
                    packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                    saasNeedRedundantAttrPoJo = formDataAddDTO.getSaasNeedRedundantAttrPoJo();
                    orderService.afterSave(saasFormSaveDTO);

                    // TODO 会影响事务回滚
                    // 导入不走回款线程保存，为了保证回款数据及时保存
                    if(!isImport) {
                        Runnable runnable = () -> {
                            try {
                                // 保存回款
                                saveLinkPayment(saasFormSaveDTO, paasFormDataEntity, saasNeedRedundantAttrPoJo, contractEntityExt);
                                saveLinkPaymentSheet(saasFormSaveDTO, paasFormDataEntity, saasNeedRedundantAttrPoJo, contractEntityExt);
                            } catch (Exception e) {
                                LOG.error("保存合同时保存回款", e);
                            }
                        };
                        threadPoolBeanConfig.addUpdateDelThreadPool().execute(runnable);
                    } else {
                        saveLinkPayment(saasFormSaveDTO, paasFormDataEntity, saasNeedRedundantAttrPoJo, contractEntityExt);
                        saveLinkPaymentSheet(saasFormSaveDTO, paasFormDataEntity, saasNeedRedundantAttrPoJo, contractEntityExt);
                    }
                    // 记录日志(有名称的格式为编号(名称)，无名称的格式为编号)
                    if(!isImport){
                        name = data.getString(OrderEnum.ORDER_NO.getAttr());
                        logName = name == null ? serialNo : sb.append(serialNo).append("（").append(name).append("）").toString();
                        memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, XbbRefTypeEnum.ORDER.getName(), logName);
                        mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.ORDER, operateTypeEnum,
                                Objects.toString(paasFormDataEntity.getId(), ""), logName, memo, formDataAddDTO.getHttpHeader());
                    }
                    break;
                case CONTACT:
                    ContactEntityExt contactEntityExt = new ContactEntityExt();
                    BeanUtil.copyProperties(paasFormDataEntity, contactEntityExt);
                    contactModel.insert(contactEntityExt);
                    dataId = contactEntityExt.getId();
                    paasFormDataEntity.setId(dataId);
                    packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                    distributorContactService.afterSave(saasFormSaveDTO);
                    // 记录日志
                    if(!isImport){
                        logName = FastJsonHelper.getStringOrDefaultFromFormData(data, DistributorContactEnum.NAME.getAttr(), "");
                        memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, XbbRefTypeEnum.DISTRIBUTOR_CONTACT.getName(), logName);
                        mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.DISTRIBUTOR_CONTACT, operateTypeEnum,
                                paasFormDataEntity.getId().toString(), logName, memo, formDataAddDTO.getHttpHeader());
                    }
                    break;
                case DISTRIBUTOR_ACCOUNT:
                    packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                    distributorAccountService.afterSave(saasFormSaveDTO);
                    break;
                case REFUND:
                    RefundEntityExt refundEntityExt = new RefundEntityExt();
                    BeanUtil.copyProperties(paasFormDataEntity, refundEntityExt);
                    // 关联产品特殊处理
                    JSONObject returnDataList = refundEntityExt.getData();
                    productArray = saasSaveHelp.formatSelectProduct4Save2(returnDataList, ReturnEnum.PRODUCTS.getAttr());
                    JSONArray invoiceArray = returnDataList.getJSONArray(ReturnEnum.INVOICES.getAttr());
                    JSONArray paymentSheetArray = returnDataList.getJSONArray(ReturnEnum.PAYMENT_SHEETS.getAttr());
                    JSONArray paymentArray = returnDataList.getJSONArray(ReturnEnum.PAYMENTS.getAttr());
                    saasSaveHelp.formatLinkBusiness4SaveBySerialNo(data, ReturnEnum.INVOICES.getAttr(), ReturnEnum.INVOICES_LINKED_TEXT.getAttr(), ReturnEnum.INVOICES.getFieldType());
                    saasSaveHelp.formatLinkBusiness4SaveBySerialNo(data, ReturnEnum.PAYMENT_SHEETS.getAttr(), ReturnEnum.PAYMENT_SHEETS_LINKED_TEXT.getAttr(), ReturnEnum.PAYMENT_SHEETS.getFieldType());
                    saasSaveHelp.formatLinkBusiness4SaveBySerialNo(data, ReturnEnum.PAYMENTS.getAttr(), ReturnEnum.PAYMENTS_LINKED_TEXT.getAttr(), ReturnEnum.PAYMENTS.getFieldType());
                    //合计退款金额在afterSave中处理，根据回款单是否创建成功来处理
                    Double refundAmount = FastJsonHelper.getDoubleOrDefaultFromFormData(data, ReturnEnum.REFUND_AMOUNT.getAttr(), 0D);
                    boolean paymentSheetIsProcess = processStartHelp.processFormJudge(corpid, XbbRefTypeEnum.PAYMENT_SHEET.getCode());
                    boolean invoiceIsProcess = processStartHelp.processFormJudge(corpid, XbbRefTypeEnum.INVOICE.getCode());
                    if (paymentSheetIsProcess) {
                        returnDataList.put(ReturnEnum.REFUND_AMOUNT.getAttr(), 0D);
                    }
                    // TODO 前端多传了参数
                    returnDataList.remove("text_8");
                    refundEntityExt.setData(returnDataList);
                    refundModel.insert(refundEntityExt);
                    dataId = refundEntityExt.getId();
                    paasFormDataEntity.setId(dataId);
                    paasFormDataEntity.getData().put(ReturnEnum.PRODUCTS.getAttr(),productArray);
                    packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                    AssociatedBusinessAfterSavePojo refundAfterSavePojo = new AssociatedBusinessAfterSavePojo(invoiceArray, paymentSheetArray, paymentArray, refundAmount, reRollBackEntity, paymentSheetIsProcess, invoiceIsProcess);
                    returnService.afterSave(saasFormSaveDTO, refundAfterSavePojo);

                    // 记录日志(有名称的格式为编号(名称)，无名称的格式为编号)
                    if(!isImport){
                        name = data.getString(ReturnEnum.RETURN_NAME.getAttr());
                        logName = name == null ? serialNo : sb.append(serialNo).append("（").append(name).append("）").toString();
                        memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, XbbRefTypeEnum.RETURN.getName(), logName);
                        mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.RETURN, operateTypeEnum,
                                paasFormDataEntity.getId().toString(), logName, memo, formDataAddDTO.getHttpHeader());
                    }
                    break;
                case CONTRACT_OUTSTOCK:
                    OutstockEntityExt outstockEntityExt = new OutstockEntityExt();
                    BeanUtil.copyProperties(paasFormDataEntity, outstockEntityExt);
                    // 关联产品特殊处理
                    JSONObject outstockDataList = outstockEntityExt.getData();
                    // 设置发货状态默认值
                    outstockDataList.put(OrderOutStockEnum.EXPRESS_STATUS.getAttr(), OrderOutStockExpressStatusEnum.TO_BE_DELIVERED.getCode());
                    productArray = saasSaveHelp.formatSelectProduct4Save2(outstockDataList, OutstockEnum.PRODUCT.getAttr());
                    outstockEntityExt.setData(outstockDataList);
                    Long modelType = fundSetService.getModelType(corpid, XbbRefTypeEnum.CRM);
                    outstockEntityExt.setSysLong10(modelType);
                    outstockModel.insert(outstockEntityExt);
                    dataId = outstockEntityExt.getId();
                    paasFormDataEntity.setId(dataId);
                    // 保存出库单后的操作
                    outstockDataList.put(OutstockEnum.PRODUCT.getAttr(),productArray);
                    paasFormDataEntity.setData(outstockDataList);
                    saasFormSaveDTO.setIsNew(true);
                    packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                    orderOutstockService.afterSave(saasFormSaveDTO);

                    // 记录日志(有名称的格式为编号(名称)，无名称的格式为编号)
                    if(!isImport){
                        logName = serialNo;
                        memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, XbbRefTypeEnum.ORDER_OUTSTOCK.getName(), logName);
                        mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.ORDER_OUTSTOCK, OperateTypeEnum.NEW,
                                paasFormDataEntity.getId().toString(), logName, memo, formDataAddDTO.getHttpHeader());
                    }
                    break;
                case CUSTOMER_COMMUNICATE:
                    JSONObject communicateData = (JSONObject) paasFormDataEntity.getData().clone();
                    List<String> atUserIds;
                    if (communicateData.getJSONArray(DistributorCommunicateEnum.AT_USERNAME.getAttr()) != null) {
                        JSONArray jsonArray = communicateData.getJSONArray(DistributorCommunicateEnum.AT_USERNAME.getAttr());
                        atUserIds = JSONArray.parseArray(jsonArray.toJSONString(),String.class);
                    } else {
                        atUserIds = saasFormSaveDTO.getSaasNeedRedundantAttrPoJo().getAtUserIds();
                        if (Objects.nonNull(atUserIds) && atUserIds.size() > 0) {
                            communicateData.put(DistributorCommunicateEnum.AT_USERNAME.getAttr(), atUserIds);
                            paasFormDataEntity.setData(communicateData);
                        }
                    }
                    CustomerCommunicateEntityExt customerCommunicateEntityExt = new CustomerCommunicateEntityExt();
                    BeanUtil.copyProperties(paasFormDataEntity, customerCommunicateEntityExt);
                    if (Objects.isNull(customerCommunicateEntityExt.getSerialNo())) {
                        customerCommunicateEntityExt.setSerialNo("");
                    }
                    customerCommunicateModel.insert(customerCommunicateEntityExt);
                    dataId = customerCommunicateEntityExt.getId();
                    paasFormDataEntity.setId(dataId);
                    // 保存客户跟进记录后的操作
                    paasFormDataEntity.setData(communicateData);
                    packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                    distributorCommunicateService.afterSave(saasFormSaveDTO);
                    // 记录日志
                    if(!isImport){
                        logName = FastJsonHelper.getStringOrDefaultFromFormData(data, DistributorCommunicateEnum.DISTRIBUTOR_NAME_LINK_TEXT.getAttr(), "");
                        memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, xbbRefTypeEnum.getName(), logName);
                        mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.DISTRIBUTOR_COMMUNICATE, operateTypeEnum,
                                paasFormDataEntity.getId().toString(), logName, memo, formDataAddDTO.getHttpHeader());
                    }
                    break;
                case PAYMENT:
                case RED_RECEIVABLES:
                    PaymentEntityExt paymentEntityExt = new PaymentEntityExt();
                    JSONObject paymentData = paasFormDataEntity.getData();
                    /*for (Map.Entry<String,Object> entry : SaasDataInitHelp.initPayment().entrySet()){
                        SaasDataInitHelp.antDataSet(paymentData,entry.getKey(),entry.getValue());
                    }*/
                    modelType = fundSetService.getModelType(corpid, XbbRefTypeEnum.CRM);
                    paasFormDataEntity.setSysLong10(modelType);
                    BeanUtil.copyProperties(paasFormDataEntity, paymentEntityExt);
                    paymentModel.insert(paymentEntityExt);
                    dataId = paymentEntityExt.getId();
                    JSONObject paymentDate=paymentEntityExt.getData();
                    Long customerId = FastJsonHelper.getLongOrDefaultFromFormData(paymentDate,PaymentEnum.CUSTOMER.getAttr(),0L);
                    Long contractId = FastJsonHelper.getLongOrDefaultFromFormData(paymentDate,PaymentEnum.CONTRACT.getAttr(),0L);
                    userTeamService.createPaymentUser(corpid,customerId,contractId,Arrays.asList(dataId), PaymentLinkTypeEnum.CONTRACT.getCode(),false);

                    paasFormDataEntity.setId(dataId);
                    packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                    afterSaveVO = paymentService.afterSave(saasFormSaveDTO);
                    // 记录日志(有名称的格式为编号(名称)，无名称的格式为编号)
                    logName = serialNo;
                    memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, xbbRefTypeEnum.getName(), logName);
                    mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.PaymentManage, operateTypeEnum,
                            paasFormDataEntity.getId().toString(), logName, memo, formDataAddDTO.getHttpHeader());
                    break;
                case PAY_PLAN:
                    PayPlanEntityExt payPlanEntityExt = new PayPlanEntityExt();
                    JSONObject payPlanData = paasFormDataEntity.getData();
                    for (Map.Entry<String,Object> entry : SaasDataInitHelp.initPayPlan().entrySet()){
                        SaasDataInitHelp.antDataSet(payPlanData,entry.getKey(),entry.getValue());
                    }
                    BeanUtil.copyProperties(paasFormDataEntity, payPlanEntityExt);
                    payPlanModel.insert(payPlanEntityExt);
                    dataId = payPlanEntityExt.getId();
                    paasFormDataEntity.setId(dataId);
                    packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                    payPlanService.afterSave(saasFormSaveDTO);

                    Long linkSupplierId = FastJsonHelper.getLongOrDefaultFromFormData(payPlanData,PayPlanEnum.LINK_SUPPLIER.getAttr(),0L);
                    Long linkPurchaseId = FastJsonHelper.getLongOrDefaultFromFormData(payPlanData,PayPlanEnum.LINK_PURCHASE.getAttr(),0L);
                    userTeamService.createPayPlanUser(corpid,linkSupplierId,linkPurchaseId,Arrays.asList(dataId),false);
                    // 记录日志(有名称的格式为编号(名称)，无名称的格式为编号)
                    if(!isImport){
                        logName = serialNo;
                        memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, xbbRefTypeEnum.getName(), logName);
                        mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.PayManage, operateTypeEnum,
                                paasFormDataEntity.getId().toString(), logName, memo, formDataAddDTO.getHttpHeader());
                    }
                    break;
                case INVOICE:
                    saasFormSaveDTO.setIsNew(true);
                    Long refundId = data.getLong(PaasConstant.REFUND_ID);
                    data.remove(PaasConstant.REFUND_ID);
                    data.remove(InvoiceEnum.UPDATE_TIME.getAttr());
                    modelType = fundSetService.getModelType(corpid, XbbRefTypeEnum.CRM);
                    paasFormDataEntity.setSysLong10(modelType);
                    InvoiceEntityExt invoiceEntityExt = new InvoiceEntityExt();
                    BeanUtil.copyProperties(paasFormDataEntity, invoiceEntityExt);
                    invoiceModel.insert(invoiceEntityExt);
                    dataId = invoiceEntityExt.getId();
                    paasFormDataEntity.setId(dataId);
                    packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                    JSONArray amountDetail = formDataAddDTO.getAmountDetail();
                    if(Objects.nonNull(amountDetail)){
                        saasFormSaveDTO.setAmountDetail(amountDetail);
                    }
                    invoiceService.afterSave(saasFormSaveDTO);
                    if(Objects.equals(saasFormSaveDTO.getHasReceivables(),BasicConstant.ONE)){
                        JSONObject hasReceivable = new JSONObject();
                        hasReceivable.put(BasicConstant.HASRECEIVABLES, I18nMessageUtil.getMessage(ErrorMessageConstant.RED_INVOICE_HAS_RECEIVABLES));
                        afterSaveVO.setSpecialMsg(hasReceivable);
                    }
                    if (refundId != null){
                        refundService.updateRefundInvoiceId(refundId, paasFormDataEntity, saasFormSaveDTO);
                    }
                    // 记录日志(有名称的格式为编号(名称)，无名称的格式为编号)
                    if(!isImport){
                        logName = serialNo;
                        memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, xbbRefTypeEnum.getName(), logName);
                        mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.INVOICE, operateTypeEnum,
                                paasFormDataEntity.getId().toString(), logName, memo, formDataAddDTO.getHttpHeader());
                    }
                    break;
                case REFUND_INSTOCK:
                    JSONObject instockData = (JSONObject) paasFormDataEntity.getData().clone();
                    InstockEntityExt instockEntityExt = new InstockEntityExt();
                    BeanUtil.copyProperties(paasFormDataEntity, instockEntityExt);
                    // 关联产品特殊处理
                    JSONObject instockDataList = instockEntityExt.getData();
                    productArray = saasSaveHelp.formatSelectProduct4Save2(instockDataList, InstockEnum.PRODUCT.getAttr());
                    instockEntityExt.setData(instockDataList);

                    instockModel.insert(instockEntityExt);
                    dataId = instockEntityExt.getId();
                    paasFormDataEntity.setId(dataId);
                    // 保存入库单产品
                    saasFormSaveDTO.setIsNew(true);
                    instockData.put(InstockEnum.PRODUCT.getAttr(),productArray);
                    paasFormDataEntity.setData(instockData);
                    packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);

                    instockService.afterSave(saasFormSaveDTO);

                    // 记录日志
                    if(!isImport){
                        logName = serialNo;
                        memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, xbbRefTypeEnum.getName(), logName);
                        mongoLogHelp.buildLog(corpid, userId, userName, InstockTypeEnum.getByStockBusinessType(businessType).getOperateModuleTypeEnum(), OperateTypeEnum.NEW,
                                paasFormDataEntity.getId().toString(), logName, memo, formDataAddDTO.getHttpHeader());
                    }
                    break;
                case PAYMENT_SHEET:
                case BAD_DEBT:
                case WRITE_OFF_PREPAYMENT:
                case RED_PAYMENT_SHEET:
                case RED_WRITE_OFF_PREPAYMENT:
                case RED_WRITE_OFF_BALANCE:
                case RED_PREPAYMENT:
                case PREPAYMENT:
                    sheetFlag = true;
                    BeforeSaveVO beforeSaveVO = new BeforeSaveVO();
                    beforeSaveVO.setPaasFormDataEntity(paasFormDataEntity);
                    //经销商到这一步肯定都是无需审批的，为了paymentSheetFormDataService.save中使用
                    beforeSaveVO.setNoApprovalRequired(BasicConstant.ONE);
                    SaveVO saveVO = paymentSheetFormDataService.save(formDataAddDTO, beforeSaveVO, beforeSaveVO.getPaasFormEntityExt(), beforeSaveVO.getPaasFormDataEntity());
                    dataId = saveVO.getDataId();
                    packageSaasFormInsertSaveDTO(saasFormSaveDTO, saveVO.getPaasFormDataEntity());
                    saasFormSaveDTO.setDistributorBaseInfoEntity(formDataAddDTO.getDistributorBaseInfoEntity());
                    paymentSheetService.afterSave(saasFormSaveDTO);
                    break;
                case PAY_SHEET:
                case PREPAY:
                case WRITE_OFF_PREPAY:
                case RED_WRITE_OFF_PAY:
                case RED_WRITE_OFF_PREPAY:
                case RED_PREPAY:
                case BAD_PAY:
                    sheetFlag = true;
                    beforeSaveVO = new BeforeSaveVO();
                    beforeSaveVO.setPaasFormDataEntity(paasFormDataEntity);
                    //经销商到这一步肯定都是无需审批的，paySheetFormDataService.save中使用
                    beforeSaveVO.setNoApprovalRequired(BasicConstant.ONE);
                    saveVO = paySheetFormDataService.save(formDataAddDTO, beforeSaveVO, beforeSaveVO.getPaasFormEntityExt(), beforeSaveVO.getPaasFormDataEntity());
                    dataId = saveVO.getDataId();
                    packageSaasFormInsertSaveDTO(saasFormSaveDTO, saveVO.getPaasFormDataEntity());
                    payPlanSheetService.afterSave(saasFormSaveDTO);
                    break;
                case PAYMENT_TASK:
                    PaymentTaskEntityExt paymentTaskEntityExt = new PaymentTaskEntityExt();
                    BeanUtil.copyProperties(paasFormDataEntity, paymentTaskEntityExt);
                    modelType = fundSetService.getModelType(corpid, XbbRefTypeEnum.CRM);
                    paymentTaskEntityExt.setSysLong10(modelType);
                    paymentTaskModel.insert(paymentTaskEntityExt);
                    dataId = paymentTaskEntityExt.getId();
                    paasFormDataEntity.setId(dataId);
                    //保存回款计划的后续操作
                    packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                    paymentTaskService.afterSave(saasFormSaveDTO);
                    // 记录日志
                    if(!isImport){
                        logName = paymentTaskEntityExt.getSerialNo();
                        memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, xbbRefTypeEnum.getName(), paymentTaskEntityExt.getSerialNo());
//                        mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.PAYMENT_TASK_PUSH_SET, operateTypeEnum, paasFormDataEntity.getId().toString(), logName, memo, formDataAddDTO.getHttpHeader());
                    }
                    break;
                case CREDIT_LIMIT:
                    CreditLimitEntityExt creditEntityExt = new CreditLimitEntityExt();
                    BeanUtil.copyProperties(paasFormDataEntity, creditEntityExt);
                    // 提取固定额度，给固定额度赋默认值0
                    Double fixedLimit = data.getDouble(CreditLimitEnum.FIXED_LIMIT.getAttr());
                    data.put(CreditLimitEnum.FIXED_LIMIT.getAttr(), 0);
                    creditLimitModel.insert(creditEntityExt);
                    dataId = creditEntityExt.getId();
                    paasFormDataEntity.setId(dataId);
                    packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                    creditLimitService.afterSave(saasFormSaveDTO);
                    // 记录日志
                    if(!isImport){
                        logName = formDataAddDTO.getSerialNo();
                        memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, xbbRefTypeEnum.getName(), logName);
                        mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.CREDIT_LIMIT, operateTypeEnum,
                                paasFormDataEntity.getId().toString(), logName, memo, formDataAddDTO.getHttpHeader());
                    }
                    // 固定额度处理
                    if (fixedLimit.compareTo(0D) > 0) {
                        FormDataAddDTO formDataSaveDTO = creditLimitService.setFixedFormDataAddDTO(saasFormSaveDTO, fixedLimit);
                        paasFormDataService.add(formDataSaveDTO);
                    }
                    break;
                case CREDIT_TEMPORARY_LIMIT:
                    CreditTemporaryLimitEntityExt creditTemporaryEntityExt = new CreditTemporaryLimitEntityExt();
                    BeanUtil.copyProperties(paasFormDataEntity, creditTemporaryEntityExt);
                    creditTemporaryLimitModel.insert(creditTemporaryEntityExt);
                    dataId = creditTemporaryEntityExt.getId();
                    paasFormDataEntity.setId(dataId);
                    packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                    creditTemporaryLimitService.afterSave(saasFormSaveDTO);
                    // 记录日志
                    if(!isImport){
                        logName = formDataAddDTO.getSerialNo();
                        memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, xbbRefTypeEnum.getName(), logName);
                        mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.CREDIT_TEMPORARY_LIMIT, operateTypeEnum,
                                paasFormDataEntity.getId().toString(), logName, memo, formDataAddDTO.getHttpHeader());
                    }
                    break;
                case CREDIT_FIXED_LIMIT:
                    CreditFixedLimitEntityExt creditFixedEntityExt = new CreditFixedLimitEntityExt();
                    BeanUtil.copyProperties(paasFormDataEntity, creditFixedEntityExt);
                    creditFixedLimitModel.insert(creditFixedEntityExt);
                    dataId = creditFixedEntityExt.getId();
                    paasFormDataEntity.setId(dataId);
                    packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                    creditFixedLimitService.afterSave(saasFormSaveDTO);
                    // 记录日志
                    if(!isImport){
                        logName = formDataAddDTO.getSerialNo();
                        memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, xbbRefTypeEnum.getName(), logName);
                        mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.CREDIT_FIXED_LIMIT, operateTypeEnum,
                                paasFormDataEntity.getId().toString(), logName, memo, formDataAddDTO.getHttpHeader());
                    }
                    break;
                case ONLINE_PAYMENT_FLOW:
                    OnlinePaymentFlowEntity onlinePaymentFlowEntity = new OnlinePaymentFlowEntity();
                    BeanUtil.copyProperties(paasFormDataEntity, onlinePaymentFlowEntity);
                    onlinePaymentFlowModel.insert(onlinePaymentFlowEntity);
                    break;
                default:
                    throw new XbbException(TemplateErrorCodeEnum.API_ERROR_350006);
            }
            //TODO   先判断是否有文件，再进行处理，不要进行不必要的循环   2019年7月11日14:49:57
            //文件柜数据保存
            cabinetFileService.saveDataCabinetFile(formDataAddDTO.getExplainMap(), paasFormDataEntity, corpid, dataId, businessType, userId);
            //富文本数据保存
            richTextService.saveFormRichText(formDataAddDTO, paasFormDataEntity, richTextData);
        } catch (XbbException e) {
            LOG.warn(BuinessDefaultErrorCodeEnum.API_ERROR_200018.getMsg(),e);
            if (sheetFlag) {
                dataId = paasFormDataEntity.getId();
            }
            proEsHelper.physicalDeleteAllInAdd(dataId,corpid,businessType,saasMark);
            String type = String.valueOf(businessType);
            Runnable runnable = () -> {
                try {
                    proEsHelper.otherRefEsDataRollBack(paasFormDataEntity,corpid,type,saasMark, reRollBackEntity);
                } catch (Exception e2) {
                    LOG.error("回滚其他表数据失败", e2);
                }
            };
            threadPoolBeanConfig.addUpdateDelThreadPool().execute(runnable);
            throw e;
        } catch (Exception e){
            LOG.error(BuinessDefaultErrorCodeEnum.API_ERROR_200018.getMsg(),e);
            if (sheetFlag) {
                dataId = paasFormDataEntity.getId();
            }
            proEsHelper.physicalDeleteAllInAdd(dataId,corpid,businessType,saasMark);
            String type = String.valueOf(businessType);
            Runnable runnable = () -> {
                try {
                    proEsHelper.otherRefEsDataRollBack(paasFormDataEntity,corpid,type,saasMark, reRollBackEntity);
                } catch (Exception e2) {
                    LOG.error("回滚其他表数据失败", e2);
                }
            };
            threadPoolBeanConfig.addUpdateDelThreadPool().execute(runnable);
            throw new XbbException(BuinessDefaultErrorCodeEnum.API_ERROR_200018);
        }
        afterSaveVO.setFormDataId(dataId);
        return afterSaveVO;
    }

    /**
     * 设置产品默认值，这些值保存在关联表
     *
     * @param childData
     */
    private void setProductDefaultData(JSONObject childData) {
        if (Objects.isNull(childData.get(ProductEnum.COST.getAttr()))) {
            childData.put(ProductEnum.COST.getAttr(), 0.0);
        }
        if (Objects.isNull(childData.get(ProductEnum.PRICE.getAttr()))) {
            childData.put(ProductEnum.PRICE.getAttr(), 0.0);
        }
        if (Objects.isNull(childData.get(ProductEnum.STOCK.getAttr()))) {
            childData.put(ProductEnum.STOCK.getAttr(), 0.0);
        }
        if (Objects.nonNull(childData.get(ProductEnum.STOCK_NOTIFY.getAttr()))) {
            childData.put(ProductEnum.STOCK_NOTIFY.getAttr(), null);
        }
    }
    @Override
    public void saveLinkPayPlan(SaasFormSaveDTO saasFormSaveDTO, PaasFormDataEntity paasFormDataEntity, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPoJo, PurchaseEntityExt purchaseEntityExt) throws XbbException {
        if (saasNeedRedundantAttrPoJo != null && saasNeedRedundantAttrPoJo.getAddBatchDTO() != null) {
            Long purchaseId = purchaseEntityExt.getId();
            PayPlanDTO payPlanDTO = new PayPlanDTO();
            payPlanDTO.setIsImport(saasFormSaveDTO.getIsImport());
            payPlanDTO.setParentNew(true);
            payPlanDTO.setOwnerId(saasFormSaveDTO.getOwnerId());
            payPlanDTO.setCoUserId(saasFormSaveDTO.getCoUserId());
            BeanUtil.copyProperties(saasNeedRedundantAttrPoJo.getAddBatchDTO(), payPlanDTO);
            payPlanDTO.setBelonger(FastJsonHelper.getStringOrDefaultFromFormData(purchaseEntityExt.getData(),PurchaseEnum.SIGNER_ID.getAttr(),""));
            // TODO 审批过来的数据是最后审批人的userId
            payPlanDTO.setProcessCreatorId(purchaseEntityExt.getCreatorId());


            if (!payPlanDTO.getAddBatchList().isEmpty() && !Objects.equals(payPlanDTO.getIsImport(), BasicConstant.ONE)) {
                //非导入时判断数据量限制
                Integer oneStatus = packageStatusHelp.getPackageStatus(saasFormSaveDTO.getCorpid(), ValueAddedTypeEnum.ONE_FORM_DATA_NUM, payPlanDTO.getAddBatchList().size(), XbbRefTypeEnum.PAY_PLAN,
                        null);
                Integer allStatus = packageStatusHelp.getPackageStatus(saasFormSaveDTO.getCorpid(), ValueAddedTypeEnum.TOTAL_FORM_DATA_NUM, payPlanDTO.getAddBatchList().size());
                if ( !Objects.equals(oneStatus, PackageStatusEnum.NORMAL.getCode()) && !Objects.equals(oneStatus, PackageStatusEnum.WARNING.getCode()) ) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100074, I18nStringConstant.SINGLE_TABLE_NUM_LIMIT);
                }

                if ( !Objects.equals(allStatus, PackageStatusEnum.NORMAL.getCode()) && !Objects.equals(allStatus, PackageStatusEnum.WARNING.getCode()) ) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100074, I18nStringConstant.TOTAL_TABLE_NUM_LIMIT);
                }
            }

            for (AddMuchFieldPojo addMuchFieldPojo : payPlanDTO.getAddBatchList()) {
                addMuchFieldPojo.getData().put(PayPlanEnum.LINK_PURCHASE.getAttr(), purchaseId.toString());
                addMuchFieldPojo.getData().put(PayPlanEnum.LINK_PURCHASE_LINK_TEXT.getAttr(), purchaseEntityExt.getSerialNo());
            }
            payPlanService.payPlan(payPlanDTO);
        }
    }

    @Override
    public void saveLinkPayPlanSheet(SaasFormSaveDTO saasFormSaveDTO, PaasFormDataEntity paasFormDataEntity, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPoJo, PurchaseEntityExt purchaseEntityExt) throws XbbException {

        Double realPayTotalAmount = 0.0D;
        Long supplierId = FastJsonHelper.getLongOrDefaultFromFormData(purchaseEntityExt.getData(),PurchaseEnum.SUPPLIER_ID.getAttr(),0L);
        Long purchaseId = purchaseEntityExt.getId();
        PayPlanSheetDTO payPlanSheetDTO = new PayPlanSheetDTO();
        payPlanSheetDTO.setIsImport(saasFormSaveDTO.getIsImport());
        payPlanSheetDTO.setParentNew(true);
        payPlanSheetDTO.setOwnerId(saasFormSaveDTO.getOwnerId());
        payPlanSheetDTO.setCoUserId(saasFormSaveDTO.getCoUserId());
        // TODO 审批过来的数据是最后审批人的userId
        payPlanSheetDTO.setProcessCreatorId(purchaseEntityExt.getCreatorId());

        List<AddMuchFieldPojo> writeOffPreSheets = new ArrayList<>();
        List<AddMuchFieldPojo> writeOffSheets = new ArrayList<>();

        if (saasNeedRedundantAttrPoJo != null && saasNeedRedundantAttrPoJo.getAddWriteOffPrepaymentBatchDTO() != null) {
            writeOffPreSheets = saasNeedRedundantAttrPoJo.getAddWriteOffPrepaymentBatchDTO().getAddBatchList();
        }

        if (saasNeedRedundantAttrPoJo != null && saasNeedRedundantAttrPoJo.getAddPaymentSheetBatchDTO() != null) {
            writeOffSheets = saasNeedRedundantAttrPoJo.getAddPaymentSheetBatchDTO().getAddBatchList();
        }
        Integer count  = writeOffPreSheets.size() + writeOffSheets.size();
        if (!Objects.equals(saasFormSaveDTO.getIsImport(), BasicConstant.ONE)) {
            //非导入时判断数据量限制
            Integer oneStatus = packageStatusHelp.getPackageStatus(saasFormSaveDTO.getCorpid(), ValueAddedTypeEnum.ONE_FORM_DATA_NUM, count, XbbRefTypeEnum.PAY_PLAN,
                    null);
            Integer allStatus = packageStatusHelp.getPackageStatus(saasFormSaveDTO.getCorpid(), ValueAddedTypeEnum.TOTAL_FORM_DATA_NUM, count);
            if ( !Objects.equals(oneStatus, PackageStatusEnum.NORMAL.getCode()) && !Objects.equals(oneStatus, PackageStatusEnum.WARNING.getCode()) ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100074, I18nStringConstant.SINGLE_TABLE_NUM_LIMIT);
            }

            if ( !Objects.equals(allStatus, PackageStatusEnum.NORMAL.getCode()) && !Objects.equals(allStatus, PackageStatusEnum.WARNING.getCode()) ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100074, I18nStringConstant.TOTAL_TABLE_NUM_LIMIT);
            }
        }


        if (saasNeedRedundantAttrPoJo != null && saasNeedRedundantAttrPoJo.getAddWriteOffPrepaymentBatchDTO() != null) {
            payPlanSheetDTO.setLinkContractEntity(paasFormDataEntity);
            BeanUtil.copyProperties(saasNeedRedundantAttrPoJo.getAddWriteOffPrepaymentBatchDTO(), payPlanSheetDTO);
            for (AddMuchFieldPojo addMuchFieldPojo : payPlanSheetDTO.getAddBatchList()) {
                addMuchFieldPojo.getData().put(PaySheetEnum.LINK_PURCHASE.getAttr(), Arrays.asList(purchaseId.toString()));
                addMuchFieldPojo.getData().put(PaySheetEnum.PURCHASE_LINK_TEXT.getAttr(), Arrays.asList(purchaseEntityExt.getSerialNo()));
            }
            payPlanSheetDTO.setProcessCreatorId(purchaseEntityExt.getCreatorId());
            PayPlanSheetAmountVO payPlanSheetAmountVO = payPlanSheetService.addBatchForWorkflow(payPlanSheetDTO,PaySheetTypeEnum.WRITE_OFF_PREPAY,supplierId);
            realPayTotalAmount = Arith.add(realPayTotalAmount, payPlanSheetAmountVO.getRealPayTotalAmount());
        }
        if (saasNeedRedundantAttrPoJo != null && saasNeedRedundantAttrPoJo.getAddPaymentSheetBatchDTO() != null) {
            payPlanSheetDTO.setLinkContractEntity(paasFormDataEntity);
            BeanUtil.copyProperties(saasNeedRedundantAttrPoJo.getAddPaymentSheetBatchDTO(), payPlanSheetDTO);
            // TODO 审批过来的数据是最后审批人的userId
            payPlanSheetDTO.setProcessCreatorId(purchaseEntityExt.getCreatorId());
            for (AddMuchFieldPojo addMuchFieldPojo : payPlanSheetDTO.getAddBatchList()) {
                addMuchFieldPojo.getData().put(PaySheetEnum.LINK_PURCHASE.getAttr(), Arrays.asList(purchaseId.toString()));
                addMuchFieldPojo.getData().put(PaySheetEnum.PURCHASE_LINK_TEXT.getAttr(), Arrays.asList(purchaseEntityExt.getSerialNo()));
            }
            PayPlanSheetAmountVO payPlanSheetAmountVO = payPlanSheetService.addBatchForWorkflow(payPlanSheetDTO,PaySheetTypeEnum.WRITE_OFF_PAY,supplierId);
            realPayTotalAmount = Arith.add(realPayTotalAmount, payPlanSheetAmountVO.getRealPayTotalAmount());
        }
        if ( realPayTotalAmount>0.0D ){
            purchaseService.updateProfit(saasFormSaveDTO.getCorpid(),realPayTotalAmount,purchaseId,purchaseEntityExt);
        }
    }

    private void saveLinkPayment(SaasFormSaveDTO saasFormSaveDTO, PaasFormDataEntity paasFormDataEntity, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPoJo, ContractEntityExt contractEntityExt) throws XbbException {
        if (saasNeedRedundantAttrPoJo != null && saasNeedRedundantAttrPoJo.getAddBatchDTO() != null) {
            Long contractId = contractEntityExt.getId();
            PaymentDTO paymentDTO = new PaymentDTO();
            paymentDTO.setOwnerId(saasFormSaveDTO.getOwnerId());
            paymentDTO.setCoUserId(saasFormSaveDTO.getCoUserId());
            paymentDTO.setIsImport(saasFormSaveDTO.getIsImport());
            paymentDTO.setParentNew(true);
            paymentDTO.setLinkContractEntity(paasFormDataEntity);
            BeanUtil.copyProperties(saasNeedRedundantAttrPoJo.getAddBatchDTO(), paymentDTO);
            // TODO 审批过来的数据是最后审批人的userId
            paymentDTO.setProcessCreatorId(contractEntityExt.getCreatorId());

            if (!paymentDTO.getAddBatchList().isEmpty() && !Objects.equals(paymentDTO.getIsImport(), BasicConstant.ONE)) {
                //非导入时判断数据量限制
                Integer oneStatus = packageStatusHelp.getPackageStatus(saasFormSaveDTO.getCorpid(), ValueAddedTypeEnum.ONE_FORM_DATA_NUM, paymentDTO.getAddBatchList().size(), XbbRefTypeEnum.PAYMENT,
                        null);
                Integer allStatus = packageStatusHelp.getPackageStatus(saasFormSaveDTO.getCorpid(), ValueAddedTypeEnum.TOTAL_FORM_DATA_NUM, paymentDTO.getAddBatchList().size());
                if ( !Objects.equals(oneStatus, PackageStatusEnum.NORMAL.getCode()) && !Objects.equals(oneStatus, PackageStatusEnum.WARNING.getCode()) ) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100074, I18nStringConstant.SINGLE_TABLE_NUM_LIMIT);
                }

                if ( !Objects.equals(allStatus, PackageStatusEnum.NORMAL.getCode()) && !Objects.equals(allStatus, PackageStatusEnum.WARNING.getCode()) ) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100074, I18nStringConstant.TOTAL_TABLE_NUM_LIMIT);
                }
            }

            for (AddMuchFieldPojo addMuchFieldPojo : paymentDTO.getAddBatchList()) {
                addMuchFieldPojo.getData().put(PaymentEnum.CONTRACT.getAttr(), contractId.toString());
                addMuchFieldPojo.getData().put(PaymentEnum.CONTRACT_LINK_TEXT.getAttr(), contractEntityExt.getSerialNo());
            }
            paymentService.pay(paymentDTO);
        }
    }

    private void saveLinkPaymentSheet(SaasFormSaveDTO saasFormSaveDTO, PaasFormDataEntity paasFormDataEntity, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPoJo, ContractEntityExt contractEntityExt) throws XbbException {
        Double realPaymentTotalAmount = 0.0D;
        Long customerId = FastJsonHelper.getLongOrDefaultFromFormData(contractEntityExt.getData(),ContractEnum.LINK_CUSTOMER.getAttr(),0L);
        Long contractId = contractEntityExt.getId();

        List<AddMuchFieldPojo> writeOffPreSheets = new ArrayList<>();
        List<AddMuchFieldPojo> writeOffSheets = new ArrayList<>();

        if (saasNeedRedundantAttrPoJo != null && saasNeedRedundantAttrPoJo.getAddWriteOffPrepaymentBatchDTO() != null) {
            writeOffPreSheets = saasNeedRedundantAttrPoJo.getAddWriteOffPrepaymentBatchDTO().getAddBatchList();
        }

        if (saasNeedRedundantAttrPoJo != null && saasNeedRedundantAttrPoJo.getAddPaymentSheetBatchDTO() != null) {
            writeOffSheets = saasNeedRedundantAttrPoJo.getAddPaymentSheetBatchDTO().getAddBatchList();
        }
        Integer count  = writeOffPreSheets.size() + writeOffSheets.size();
        if (!Objects.equals(saasFormSaveDTO.getIsImport(), BasicConstant.ONE)) {
            //非导入时判断数据量限制
            Integer oneStatus = packageStatusHelp.getPackageStatus(saasFormSaveDTO.getCorpid(), ValueAddedTypeEnum.ONE_FORM_DATA_NUM, count, XbbRefTypeEnum.PAYMENT_SHEET,
                    null);
            Integer allStatus = packageStatusHelp.getPackageStatus(saasFormSaveDTO.getCorpid(), ValueAddedTypeEnum.TOTAL_FORM_DATA_NUM, count);
            if ( !Objects.equals(oneStatus, PackageStatusEnum.NORMAL.getCode()) && !Objects.equals(oneStatus, PackageStatusEnum.WARNING.getCode()) ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100074, I18nStringConstant.SINGLE_TABLE_NUM_LIMIT);
            }

            if ( !Objects.equals(allStatus, PackageStatusEnum.NORMAL.getCode()) && !Objects.equals(allStatus, PackageStatusEnum.WARNING.getCode()) ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100074, I18nStringConstant.TOTAL_TABLE_NUM_LIMIT);
            }
        }

        if (saasNeedRedundantAttrPoJo != null && saasNeedRedundantAttrPoJo.getAddWriteOffPrepaymentBatchDTO() != null) {
            PaymentSheetDTO paymentSheetDTO = new PaymentSheetDTO();
            paymentSheetDTO.setOwnerId(saasFormSaveDTO.getOwnerId());
            paymentSheetDTO.setCoUserId(saasFormSaveDTO.getCoUserId());
            paymentSheetDTO.setIsImport(saasFormSaveDTO.getIsImport());
            paymentSheetDTO.setParentNew(true);
            paymentSheetDTO.setLinkContractEntity(paasFormDataEntity);
            BeanUtil.copyProperties(saasNeedRedundantAttrPoJo.getAddWriteOffPrepaymentBatchDTO(), paymentSheetDTO);
            // TODO 审批过来的数据是最后审批人的userId
            paymentSheetDTO.setProcessCreatorId(contractEntityExt.getCreatorId());
            for (AddMuchFieldPojo addMuchFieldPojo : paymentSheetDTO.getAddBatchList()) {
                addMuchFieldPojo.getData().put(PaymentSheetEnum.CONTRACT.getAttr(), Arrays.asList(contractId.toString()));
                addMuchFieldPojo.getData().put(PaymentSheetEnum.CONTRACT_LINK_TEXT.getAttr(), Arrays.asList(contractEntityExt.getSerialNo()));
            }
            PaymentSheetAmountVO writeOffPrepaymentAmountVO = paymentSheetService.addBatchForWorkflow(paymentSheetDTO, PaymentSheetTypeEnum.WRITE_OFF_PREPAYMENT, customerId);
            realPaymentTotalAmount = writeOffPrepaymentAmountVO.getRealPaymentTotalAmount();
        }
        if (saasNeedRedundantAttrPoJo != null && saasNeedRedundantAttrPoJo.getAddPaymentSheetBatchDTO() != null) {
            PaymentSheetDTO paymentSheetDTO = new PaymentSheetDTO();
            paymentSheetDTO.setOwnerId(saasFormSaveDTO.getOwnerId());
            paymentSheetDTO.setCoUserId(saasFormSaveDTO.getCoUserId());
            paymentSheetDTO.setIsImport(saasFormSaveDTO.getIsImport());
            paymentSheetDTO.setParentNew(true);
            paymentSheetDTO.setLinkContractEntity(paasFormDataEntity);
            BeanUtil.copyProperties(saasNeedRedundantAttrPoJo.getAddPaymentSheetBatchDTO(), paymentSheetDTO);
            // TODO 审批过来的数据是最后审批人的userId
            paymentSheetDTO.setProcessCreatorId(contractEntityExt.getCreatorId());
            for (AddMuchFieldPojo addMuchFieldPojo : paymentSheetDTO.getAddBatchList()) {
                addMuchFieldPojo.getData().put(PaymentSheetEnum.CONTRACT.getAttr(), Arrays.asList(contractId.toString()));
                addMuchFieldPojo.getData().put(PaymentSheetEnum.CONTRACT_LINK_TEXT.getAttr(), Arrays.asList(contractEntityExt.getSerialNo()));
            }

            PaymentSheetAmountVO writeOffAmountVO = paymentSheetService.addBatchForWorkflow(paymentSheetDTO, PaymentSheetTypeEnum.WRITE_OFF, customerId);
            Double addPaymentAmount = writeOffAmountVO.getRealPaymentTotalAmount();
            realPaymentTotalAmount = Arith.add(realPaymentTotalAmount, addPaymentAmount);
        }

        /**
         * 处理合同的已收款金额，未收款金额，坏账金额
         * @author chenshan
         * @date 2019-11-30 12:56
         */
        if ( realPaymentTotalAmount>0.0D ) {
            // 更新现金毛利
            contractService.updateCashProfit(saasFormSaveDTO.getCorpid(), realPaymentTotalAmount, contractId, contractEntityExt, saasFormSaveDTO.getDistributorMark());
        }
    }

    @Override
    public void setDefaultData(RedundantTemplateTypeEnum redundantTemplateTypeEnum, JSONObject dataList) {
        switch (redundantTemplateTypeEnum) {
            case PRODUCT:
                if (Objects.isNull(dataList.get(ProductEnum.COST.getAttr()))) {
                    dataList.put(ProductEnum.COST.getAttr(), 0.0);
                }
                if (Objects.isNull(dataList.get(ProductEnum.PRICE.getAttr()))) {
                    dataList.put(ProductEnum.PRICE.getAttr(), 0.0);
                }
                if (Objects.isNull(dataList.get(ProductEnum.STOCK.getAttr()))) {
                    dataList.put(ProductEnum.STOCK.getAttr(), 0.0);
                }
                if (Objects.nonNull(dataList.get(ProductEnum.STOCK_NOTIFY.getAttr()))) {
                    dataList.put(ProductEnum.STOCK_NOTIFY.getAttr(), null);
                }
                break;
            case INVENTORY:
                if (Objects.isNull(dataList.get(InventoryEnum.INSTOCK_ID.getAttr()))) {
                    dataList.put(InventoryEnum.INSTOCK_ID.getAttr(), 0);
                }
                if (Objects.isNull(dataList.get(InventoryEnum.OUTSTOCK_ID.getAttr()))) {
                    dataList.put(InventoryEnum.OUTSTOCK_ID.getAttr(), 0);
                }
                break;
            case WAREHOUSE:
                if (Objects.isNull(dataList.get(WarehouseEnum.ORI_STOCK.getAttr()))) {
                    dataList.put(WarehouseEnum.ORI_STOCK.getAttr(), WarehouseOriStockEnum.NOT_DONE.getCode());
                }
                break;
            default:
                break;
        }
    }

    /**
     * 避免代码冗余，提起数据封装
     *
     * @param saasFormSaveDTO    入参
     * @param paasFormDataEntity 数据实体
     * @date 2019/1/28 14:34
     */
    private void packageSaasFormInsertSaveDTO(SaasFormSaveDTO saasFormSaveDTO, PaasFormDataEntity paasFormDataEntity) {
        saasFormSaveDTO.setIsNew(true);
        saasFormSaveDTO.setOldData(paasFormDataEntity.getData());
        saasFormSaveDTO.setNewData(paasFormDataEntity.getData());
        saasFormSaveDTO.setNewPaasFormDataEntity(paasFormDataEntity);
        saasFormSaveDTO.setOldPaasFormDataEntity(paasFormDataEntity);
    }

    /**
     * 更新保存后封装入参
     *
     * @param saasFormSaveDTO       保存实体后逻辑入参
     * @param paasFormDataEntity    新实体
     * @param oldPaasFormDataEntity 老实体
     * @author feng.zheng
     * @date 2019/1/30 10:19
     */
    private void packageSaasFormUpdateSaveDTO(SaasFormSaveDTO saasFormSaveDTO, PaasFormDataEntity paasFormDataEntity, PaasFormDataEntity oldPaasFormDataEntity) {
        saasFormSaveDTO.setIsNew(false);
        saasFormSaveDTO.setOldPaasFormDataEntity(oldPaasFormDataEntity);
        saasFormSaveDTO.setNewPaasFormDataEntity(paasFormDataEntity);
        saasFormSaveDTO.setNewData(paasFormDataEntity.getData());
        saasFormSaveDTO.setOldData(oldPaasFormDataEntity.getData());
    }

    @Override
    public AfterSaveVO update(FormDataUpdateDTO formDataUpdateDTO, PaasFormDataEntity paasFormDataEntity, PaasFormDataEntity oldPaasFormDataEntity, PaasFormEntityExt paasFormEntityExt) throws XbbException {
        AfterSaveVO afterSaveVO = new AfterSaveVO();
        String corpid = formDataUpdateDTO.getCorpid();
        String userId = formDataUpdateDTO.getUserId();
        String creatorId = paasFormDataEntity.getCreatorId();
        String creatName = "";
        if(StringUtil.isNotEmpty(creatorId)){
            // 走审批时获取创建人id
            UserEntity user = userModel.getByKeyIngoreDel(creatorId, corpid);
            if (Objects.nonNull(user)) {
                creatName = user.getName();
            }
        }
        Integer distributorMark = paasFormEntityExt == null ? formDataUpdateDTO.getDistributorMark() : paasFormEntityExt.getDistributorMark();
        String userName = Objects.equals(paasFormDataEntity.getFlowStatus(), 2) ? creatName : formDataUpdateDTO.getLoginUserName();
        userId = Objects.equals(paasFormDataEntity.getFlowStatus(), 2) ? creatorId : userId;
        Integer saasMark = formDataUpdateDTO.getSaasMark();
        boolean isCoverage = Objects.equals(1, formDataUpdateDTO.getIsImport());
        Integer businessType = formDataUpdateDTO.getBusinessType();
        //newObj放到switch内，是因为内部把paasFormDataEntity复制给了相应对象去保存，导致原paasFormDataEntity内部分字段与更新后的实体不一致，生成的日志不准确
        JSONObject newObj;
        RedundantTemplateTypeEnum redundantTemplateTypeEnum;
        String opObjectName;
        OperateModuleTypeEnum operateModuleTypeEnum = null;
        JSONObject data = paasFormDataEntity.getData();
        paasFormDataEntity.getData().remove(FieldTypeEnum.OWNERID.getAlias());
        paasFormDataEntity.getData().remove(FieldTypeEnum.COUSERID.getAlias());
        paasFormDataEntity.getData().remove(FieldTypeEnum.SERIALNO.getAlias());
        paasFormDataEntity.getData().remove(FieldTypeEnum.UPDATETIME.getAlias());
        paasFormDataEntity.getData().remove(FieldTypeEnum.ADDTIME.getAlias());
        ReRollBackEntity reRollBackEntity = new ReRollBackEntity();
        try {
            int updateLine = 1;
            if (businessType == null || businessType == 0) {
                LOG.error("businessType为空");
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }
            SaasFormSaveDTO saasFormSaveDTO = new SaasFormSaveDTO();
            BeanUtil.copyProperties(formDataUpdateDTO, saasFormSaveDTO);
            saasFormSaveDTO.setBusinessType(businessType);
            redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(businessType);

            Long dataId = paasFormDataEntity.getId();
            JSONObject oldData = oldPaasFormDataEntity.getData();
            String serialNo = paasFormDataEntity.getSerialNo();
            List<ValidateDataDTO> needAddValidateDataDTO = null;
            List<ValidateDataDTO> needDelValidateDataDTO = null;
            List<ValidateDataDTO> needUpdateValidateDataDTO = null;
            StringBuilder sb = new StringBuilder();
            switch (redundantTemplateTypeEnum) {
                case CUSTOMER:
                    //TODO 剔除联系人
                    String oldCustomerName = FastJsonHelper.getStringOrDefaultFromFormData(oldData, CustomerManagementEnum.NAME.getAttr(), "");
                    Long oldLastConnectTime = FastJsonHelper.getLongOrDefaultFromFormData(oldData, CustomerManagementEnum.LAST_CONNECT_TIME.getAttr(), 0L);
                    data = paasFormDataEntity.getData();
                    Long newLastConnectTime = FastJsonHelper.getLongOrDefaultFromFormData(data, CustomerManagementEnum.LAST_CONNECT_TIME.getAttr(), 0L);
                    opObjectName = data.getString(CustomerManagementEnum.NAME.getAttr());
                    data.remove(CustomerManagementEnum.ADD_CONTACT.getAttr());
                    if ( oldLastConnectTime > newLastConnectTime ) {
                        data.put(CustomerManagementEnum.LAST_CONNECT_TIME.getAttr(),oldLastConnectTime);
                    }
                    paasFormDataEntity.setData(data);
                    CustomerEntityExt customerEntityExt = new CustomerEntityExt();
                    BeanUtil.copyProperties(paasFormDataEntity, customerEntityExt);
                    updateLine = customerModel.update(customerEntityExt);
                    packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                    distributorManageService.afterSave(saasFormSaveDTO);
                    SaasNeedRedundantAttrPojo saasNeedRedundantAttrPoJo = formDataUpdateDTO.getSaasNeedRedundantAttrPoJo();

                    if (saasNeedRedundantAttrPoJo != null) {
                        needAddValidateDataDTO = saasNeedRedundantAttrPoJo.getNeedAddValidateDataDTO();
                        needDelValidateDataDTO = saasNeedRedundantAttrPoJo.getNeedDelValidateDataDTO();
                        needUpdateValidateDataDTO = saasNeedRedundantAttrPoJo.getNeedUpdateValidateDataDTO();
                    }
                    if (!Objects.isNull(needAddValidateDataDTO) || !Objects.isNull(needDelValidateDataDTO) || !Objects.isNull(needUpdateValidateDataDTO)) {
                        paasFormDataService.batchEditContact(corpid,needAddValidateDataDTO, needUpdateValidateDataDTO, needDelValidateDataDTO, customerEntityExt.getId(), opObjectName, formDataUpdateDTO.getLoginUser(),ContactEnum.CUSTOMER_NAME.getAttr(),XbbRefTypeEnum.CONTACT, formDataUpdateDTO.getProcessCreatorId(), formDataUpdateDTO.getIsFromProcess());
                    }

                    // 客户数据一致性同步
                    if (!Objects.equals(oldCustomerName, opObjectName)) {
                        ConsistencySyncRabbitMqDTO consistencySyncRabbitMqDTO = new ConsistencySyncRabbitMqDTO(customerEntityExt.getCorpid(), customerEntityExt.getId(), opObjectName);
                        consistencySyncProducer.syncData(consistencySyncRabbitMqDTO, XbbRefTypeEnum.CUSTOMER);
                    }

                    // 记录日志
                    newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(customerEntityExt));
                    operateModuleTypeEnum = OperateModuleTypeEnum.DISTRIBUTOR;
                    break;
                case CONTRACT:
                    opObjectName = data.getString(ContractEnum.NAME.getAttr());
                    String oldContractSerialNo = oldPaasFormDataEntity.getSerialNo();
                    data = paasFormDataEntity.getData();
                    String newContractSerialNo = paasFormDataEntity.getSerialNo();
                    data.remove(ContractEnum.ADD_PAYMENT.getAttr());
                    data.remove(ContractEnum.ADD_WRITE_OFF_PREPAYMENT.getAttr());
                    data.remove(ContractEnum.ADD_PAYMENT_SHEET.getAttr());
                    paasFormDataEntity.setData(data);
                    ContractEntityExt contractEntityExt = new ContractEntityExt();
                    BeanUtil.copyProperties(paasFormDataEntity, contractEntityExt);
                    // 关联产品特殊处理
                    JSONObject conDataList = contractEntityExt.getData();
                    JSONArray productArray = saasSaveHelp.formatSelectProduct4Save2(conDataList, ContractEnum.PRODUCT.getAttr());
                    contractEntityExt.setData(conDataList);

                    updateLine = contractModel.update(contractEntityExt);
                    contractEntityExt.getData().put(ContractEnum.PRODUCT.getAttr(),productArray);
                    packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);

                    // 保存合同后的操作
                    contractService.afterSave(saasFormSaveDTO);

                    saasNeedRedundantAttrPoJo = formDataUpdateDTO.getSaasNeedRedundantAttrPoJo();
                    PaymentDTO paymentDTO = new PaymentDTO();
                    if (saasNeedRedundantAttrPoJo != null ) {
                        Long customerId = FastJsonHelper.getLongOrDefaultFromFormData(contractEntityExt.getData(), ContractEnum.LINK_CUSTOMER.getAttr(), 0L);
                        if ( saasNeedRedundantAttrPoJo.getAddBatchDTO() != null ) {
                            BeanUtil.copyProperties(saasNeedRedundantAttrPoJo.getAddBatchDTO(), paymentDTO);
                            paymentDTO.setIsImport(formDataUpdateDTO.getIsImport());
                            if (Objects.nonNull(formDataUpdateDTO.getIsFromProcess()) && Objects.equals(formDataUpdateDTO.getIsFromProcess(), 1)) {
                                paymentDTO.setProcessCreatorId(paasFormDataEntity.getCreatorId());
                            }
                            paymentService.pay(paymentDTO);
                        }
                        Double realPaymentTotalAmount = 0.0D;
                        if ( saasNeedRedundantAttrPoJo.getAddWriteOffPrepaymentBatchDTO() != null ) {
                            PaymentSheetDTO paymentSheetDTO = new PaymentSheetDTO();
                            BeanUtil.copyProperties(saasNeedRedundantAttrPoJo.getAddWriteOffPrepaymentBatchDTO(), paymentSheetDTO);
                            paymentSheetDTO.setProcessCreatorId(paasFormDataEntity.getCreatorId());
                            PaymentSheetAmountVO writeOffPrepaymentAmountVO = paymentSheetService.addBatchForWorkflow(paymentSheetDTO, PaymentSheetTypeEnum.WRITE_OFF_PREPAYMENT, customerId);
                            realPaymentTotalAmount = writeOffPrepaymentAmountVO.getRealPaymentTotalAmount();
                        }
                        if ( saasNeedRedundantAttrPoJo.getAddPaymentSheetBatchDTO() != null ) {
                            PaymentSheetDTO paymentSheetDTO = new PaymentSheetDTO();
                            BeanUtil.copyProperties(saasNeedRedundantAttrPoJo.getAddPaymentSheetBatchDTO(), paymentSheetDTO);
                            paymentSheetDTO.setProcessCreatorId(paasFormDataEntity.getCreatorId());
                            PaymentSheetAmountVO writeOffAmountVO = paymentSheetService.addBatchForWorkflow(paymentSheetDTO, PaymentSheetTypeEnum.WRITE_OFF, customerId);
                            Double addPaymentAmount = writeOffAmountVO.getRealPaymentTotalAmount();
                            realPaymentTotalAmount = Arith.add(realPaymentTotalAmount, addPaymentAmount);
                        }
                        /**
                         * 处理合同的已回款金额和未收款金额，坏账金额
                         * @author chenshan
                         * @date 2019-11-30 12:47
                         */
                        if ( realPaymentTotalAmount>0.0D ) {
                            // 更新现金毛利
                            contractService.updateCashProfit(saasFormSaveDTO.getCorpid(), realPaymentTotalAmount, contractEntityExt.getId(), contractEntityExt, paasFormEntityExt.getDistributorMark());
                        }
                    }

                    if (!Objects.equals(oldContractSerialNo, newContractSerialNo)) {
                        ConsistencySyncRabbitMqDTO consistencySyncRabbitMqDTO = new ConsistencySyncRabbitMqDTO(contractEntityExt.getCorpid(), contractEntityExt.getId(), newContractSerialNo, newContractSerialNo);
                        consistencySyncProducer.syncData(consistencySyncRabbitMqDTO, XbbRefTypeEnum.CONTRACT);
                    }
                    // 记录日志
                    opObjectName = opObjectName == null ? serialNo : sb.append(serialNo).append("（").append(opObjectName).append("）").toString();
                    newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(contractEntityExt));
                    operateModuleTypeEnum = OperateModuleTypeEnum.ORDER;
                    break;
                case CONTACT:
                    opObjectName = FastJsonHelper.getStringOrDefaultFromFormData(oldData, ContactEnum.NAME.getAttr(), "");
                    JSONObject newData = paasFormDataEntity.getData();
                    String newContactName = newData.getString(ContactEnum.NAME.getAttr());
                    ContactEntityExt contactEntityExt = new ContactEntityExt();
                    BeanUtil.copyProperties(paasFormDataEntity, contactEntityExt);
                    updateLine = contactModel.update(contactEntityExt);
                    packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                    distributorContactService.afterSave(saasFormSaveDTO);

                    if (!Objects.equals(opObjectName, newContactName)) {
                        ConsistencySyncRabbitMqDTO consistencySyncRabbitMqDTO = new ConsistencySyncRabbitMqDTO(contactEntityExt.getCorpid(), contactEntityExt.getId(), newContactName);
                        consistencySyncProducer.syncData(consistencySyncRabbitMqDTO, XbbRefTypeEnum.CONTACT);
                    }
                    // 记录日志
                    newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(contactEntityExt));
                    operateModuleTypeEnum = OperateModuleTypeEnum.DISTRIBUTOR_CONTACT;
                    break;
                case COMMUNICATE:
                    CustomerCommunicateEntityExt customerCommunicateEntityExt = new CustomerCommunicateEntityExt();
                    BeanUtil.copyProperties(paasFormDataEntity, customerCommunicateEntityExt);
                    updateLine = customerCommunicateModel.update(customerCommunicateEntityExt);
                    packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                    customerCommunicateService.afterSave(saasFormSaveDTO);
                    // 记录日志
                    opObjectName = FastJsonHelper.getStringOrDefaultFromFormData(data, CustomerCommunicateEnum.CUSTOMER_NAME_LINK_TEXT.getAttr(), "");
                    newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(customerCommunicateEntityExt));
                    operateModuleTypeEnum = OperateModuleTypeEnum.CustomerCommunicate;
                    break;
                case PAYMENT:
                    PaymentStatusEnum paymentStatusEnum = PaymentStatusEnum.getByCode(oldData.getString(PaymentEnum.STATUS.getAttr()));
                    //得到编辑时禁止修改的字段list：应收款编辑是，部分特定字段不允许修改，值必须用原值
                    List<String> paymentUnableEditAttrList = PaymentBaseEnum.getUnableEditAttrList(paymentStatusEnum);
                    for (String attr : paymentUnableEditAttrList) {
                        data.put(attr, oldData.get(attr));
                    }
                    paasFormDataEntity.setData(data);
                    PaymentEntityExt paymentEntityExt = new PaymentEntityExt();
                    BeanUtil.copyProperties(paasFormDataEntity, paymentEntityExt);
                    updateLine = paymentModel.update(paymentEntityExt);
                    packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                    afterSaveVO = paymentService.afterSave(saasFormSaveDTO);
                    // 记录日志
                    opObjectName = serialNo;
                    // 负责人是获取当前登录人的ID，不准确,所属部门也没有模版字段，舍去
                    paymentEntityExt.setOwnerId(null);
                    paymentEntityExt.setDepartmentId(null);
                    // 应收款编号数据一致性同步 目前只有销项发票需要同步
                    String oldPaymentSeriNo = oldPaasFormDataEntity.getSerialNo();
                    if (!Objects.equals(oldPaymentSeriNo, serialNo)) {
                        ConsistencySyncRabbitMqDTO consistencySyncRabbitMqDTO = new ConsistencySyncRabbitMqDTO(paymentEntityExt.getCorpid(), paymentEntityExt.getId(), serialNo);
                        consistencySyncProducer.syncData(consistencySyncRabbitMqDTO, XbbRefTypeEnum.PAYMENT);
                    }
                    newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(paymentEntityExt));
                    operateModuleTypeEnum = OperateModuleTypeEnum.PaymentManage;
                    break;
                case PAY_PLAN:
                    PayPlanStatusEnum payStatusEnum = PayPlanStatusEnum.getByCode(oldData.getString(PayPlanEnum.STATUS.getAttr()));
                    //得到编辑时禁止修改的字段list：付款计划编辑是，部分特定字段不允许修改，值必须用原值
                    List<String> payUnableEditAttrList = PayPlanEnum.getUnableEditAttrList(true, payStatusEnum);
                    for (String attr : payUnableEditAttrList) {
                        data.put(attr, oldData.get(attr));
                    }
                    paasFormDataEntity.setData(data);
                    PayPlanEntityExt payPlanEntityExt = new PayPlanEntityExt();
                    BeanUtil.copyProperties(paasFormDataEntity, payPlanEntityExt);
                    updateLine = payPlanModel.update(payPlanEntityExt);
                    packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                    payPlanService.afterSave(saasFormSaveDTO);
                    // 付款计划编号数据一致性同步 目前只有销项发票需要同步
                    String oldPayPlanSeriNo = oldPaasFormDataEntity.getSerialNo();
                    if (!Objects.equals(oldPayPlanSeriNo, serialNo)) {
                        ConsistencySyncRabbitMqDTO consistencySyncRabbitMqDTO = new ConsistencySyncRabbitMqDTO(payPlanEntityExt.getCorpid(), payPlanEntityExt.getId(), serialNo);
                        consistencySyncProducer.syncData(consistencySyncRabbitMqDTO, XbbRefTypeEnum.PAY_PLAN);
                    }
                    // 记录日志
                    opObjectName = serialNo;
                    newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(payPlanEntityExt));
                    operateModuleTypeEnum = OperateModuleTypeEnum.PayManage;
                    break;
                case INVOICE:
                    invoiceCommonHelper.checkApiResultSafe(paasFormDataEntity);
                    InvoiceEntityExt invoiceEntityExt = new InvoiceEntityExt();
                    BeanUtil.copyProperties(paasFormDataEntity, invoiceEntityExt);
                    updateLine = invoiceModel.update(invoiceEntityExt);
                    packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                    invoiceService.afterSave(saasFormSaveDTO);
                    // 记录日志
                    opObjectName = serialNo;
                    newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(invoiceEntityExt));
                    operateModuleTypeEnum = OperateModuleTypeEnum.INVOICE;
                    break;
                case REFUND_INSTOCK:
                    JSONObject instockData = (JSONObject) paasFormDataEntity.getData().clone();
                    InstockEntityExt instockEntityExt = new InstockEntityExt();
                    BeanUtil.copyProperties(paasFormDataEntity, instockEntityExt);
                    // 关联产品特殊处理
                    JSONObject instockDataList = instockEntityExt.getData();
                    productArray = saasSaveHelp.formatSelectProduct4Save2(instockDataList, InstockEnum.PRODUCT.getAttr());
                    instockEntityExt.setData(instockDataList);

                    updateLine = instockModel.update(instockEntityExt);
//                        paasFormDataEntity.setId(instockEntityExt.getId());
//                        instockData.put(InstockEnum.PRODUCT.getAttr(),productArray);
//                        paasFormDataEntity.setData(instockData);
//                        packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
//                        instockService.afterSave(saasFormSaveDTO);
                    // 记录日志
                    opObjectName = serialNo;
                    newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(instockEntityExt));
                    operateModuleTypeEnum = InstockTypeEnum.getByStockBusinessType(businessType).getOperateModuleTypeEnum();
                    break;
                case CONTRACT_OUTSTOCK:
                    JSONObject outstockData = (JSONObject) paasFormDataEntity.getData().clone();
                    OutstockEntityExt outstockEntityExt = new OutstockEntityExt();
                    BeanUtil.copyProperties(paasFormDataEntity, outstockEntityExt);
                    // 关联产品特殊处理
                    JSONObject outstockDataList = outstockEntityExt.getData();
                    productArray = saasSaveHelp.formatSelectProduct4Save2(outstockDataList, OutstockEnum.PRODUCT.getAttr());
                    outstockEntityExt.setData(outstockDataList);

                    updateLine = outstockModel.update(outstockEntityExt);
                    paasFormDataEntity.setId(outstockEntityExt.getId());

                    // 保存后操作
                    outstockData.put(OutstockEnum.PRODUCT.getAttr(),productArray);
                    paasFormDataEntity.setData(outstockData);
                    packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                    orderOutstockService.afterSave(saasFormSaveDTO);
                    // 记录日志
                    opObjectName = serialNo;
                    newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(outstockEntityExt));
                    operateModuleTypeEnum = OperateModuleTypeEnum.ORDER_OUTSTOCK;
                    break;
                case REFUND:
                    RefundEntityExt refundEntityExt = new RefundEntityExt();
                    BeanUtil.copyProperties(paasFormDataEntity, refundEntityExt);
                    // 关联产品特殊处理
                    JSONObject returnDataList = refundEntityExt.getData();
                    productArray = saasSaveHelp.formatSelectProduct4Save2(returnDataList, ReturnEnum.PRODUCTS.getAttr());
                    JSONArray invoiceArray = returnDataList.getJSONArray(ReturnEnum.INVOICES.getAttr());
                    JSONArray paymentSheetArray = returnDataList.getJSONArray(ReturnEnum.PAYMENT_SHEETS.getAttr());
                    JSONArray paymentArray = returnDataList.getJSONArray(ReturnEnum.PAYMENTS.getAttr());
                    saasSaveHelp.formatLinkBusiness4SaveBySerialNo(data, ReturnEnum.INVOICES.getAttr(), ReturnEnum.INVOICES_LINKED_TEXT.getAttr(), ReturnEnum.INVOICES.getFieldType());
                    saasSaveHelp.formatLinkBusiness4SaveBySerialNo(data, ReturnEnum.PAYMENT_SHEETS.getAttr(), ReturnEnum.PAYMENT_SHEETS_LINKED_TEXT.getAttr(), ReturnEnum.PAYMENT_SHEETS.getFieldType());
                    saasSaveHelp.formatLinkBusiness4SaveBySerialNo(data, ReturnEnum.PAYMENTS.getAttr(), ReturnEnum.PAYMENTS_LINKED_TEXT.getAttr(), ReturnEnum.PAYMENTS.getFieldType());
                    refundEntityExt.setData(returnDataList);
                    updateLine = refundModel.update(refundEntityExt);
                    paasFormDataEntity.getData().put(ReturnEnum.PRODUCTS.getAttr(),productArray);
                    packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                    PaasFormEntity paymentSheetFormEntity = paasFormModel.getByBusinessType4Distributor(XbbRefTypeEnum.PAYMENT_SHEET.getCode(), corpid, distributorMark, null);
                    PaasFormEntity invoiceFormEntity = paasFormModel.getByBusinessType4Distributor(XbbRefTypeEnum.INVOICE.getCode(), corpid, distributorMark, null);
                    boolean paymentSheetIsProcess = Objects.equals(paymentSheetFormEntity.getIsProcessForm(), BasicConstant.ONE);
                    boolean invoiceIsProcess = Objects.equals(invoiceFormEntity.getIsProcessForm(), BasicConstant.ONE);
                    AssociatedBusinessAfterSavePojo refundAfterSavePojo = new AssociatedBusinessAfterSavePojo(invoiceArray, paymentSheetArray, paymentArray, null, reRollBackEntity, paymentSheetIsProcess, invoiceIsProcess);
                    returnService.afterSave(saasFormSaveDTO, refundAfterSavePojo);
                    // 记录日志
                    opObjectName = data.getString(ReturnEnum.RETURN_NAME.getAttr());
                    opObjectName = opObjectName == null ? serialNo : sb.append(serialNo).append("（").append(opObjectName).append("）").toString();
                    newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(refundEntityExt));
                    operateModuleTypeEnum = OperateModuleTypeEnum.RETURN;
                    break;
                case PAYMENT_SHEET:
                    SheetTypeEnum sheetTypeEnum = SheetTypeEnum.getByCodeRefTypeEnum(data.getString(PaymentSheetEnum.PAYMENT_SHEET_TYPE.getAttr()), XbbRefTypeEnum.PAYMENT_SHEET);
                    data = fundHelp.handlePaymentSheetData4Update(sheetTypeEnum, data, oldData, formDataUpdateDTO.getDistributorMark(), null);
                    paasFormDataEntity.setData(data);
                    PaymentSheetEntityExt paymentSheetEntityExt = new PaymentSheetEntityExt();
                    BeanUtil.copyProperties(paasFormDataEntity, paymentSheetEntityExt);
                    updateLine = paymentSheetModel.update(paymentSheetEntityExt);
                    //更新子单信息
                    List<UpdateDataEntity> updateList = saasUpdateHelp.updateSonDataList4Sheet(corpid, sheetTypeEnum, saasFormSaveDTO.getAmountDetail(), formDataUpdateDTO.getExplainMap(), DistributorMarkEnum.DISTRIBUTOR.getCode());
                    if (CollectionsUtil.isNotEmpty(updateList)) {
                        paymentSheetModel.updateBatch(updateList, corpid);
                    }
                    packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                    // 记录日志
                    opObjectName = serialNo;
                    // 负责人是获取当前登录人的ID，不准确,所属部门也没有模版字段，舍去
                    paymentSheetEntityExt.setOwnerId(null);
                    paymentSheetEntityExt.setDepartmentId(null);
                    newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(paymentSheetEntityExt));
                    operateModuleTypeEnum = OperateModuleTypeEnum.PaymentManage;
                    break;
                case PAY_SHEET:
                    sheetTypeEnum = SheetTypeEnum.getByCodeRefTypeEnum(data.getString(PaySheetEnum.PAY_SHEET_TYPE.getAttr()), XbbRefTypeEnum.PAY_SHEET);
                    data = fundHelp.handlePaymentSheetData4Update(sheetTypeEnum, data, oldData, formDataUpdateDTO.getDistributorMark(), null);
                    paasFormDataEntity.setData(data);
                    PayPlanSheetEntityExt payPlanSheetEntityExt = new PayPlanSheetEntityExt();
                    BeanUtil.copyProperties(paasFormDataEntity, payPlanSheetEntityExt);
                    updateLine = payPlanSheetModel.update(payPlanSheetEntityExt);
                    //更新子单信息
                    updateList = saasUpdateHelp.updateSonDataList4Sheet(corpid, sheetTypeEnum, saasFormSaveDTO.getAmountDetail(), formDataUpdateDTO.getExplainMap(), DistributorMarkEnum.DISTRIBUTOR.getCode());
                    if (CollectionsUtil.isNotEmpty(updateList)) {
                        payPlanSheetModel.updateBatch(updateList, corpid);
                    }
                    packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                    // 记录日志
                    opObjectName = serialNo;
                    // 负责人是获取当前登录人的ID，不准确,所属部门也没有模版字段，舍去
                    payPlanSheetEntityExt.setOwnerId(null);
                    payPlanSheetEntityExt.setDepartmentId(null);
                    newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(payPlanSheetEntityExt));
                    operateModuleTypeEnum = OperateModuleTypeEnum.PayManage;
                    break;
                case PAYMENT_TASK:
                    PaymentTaskEntityExt paymentTaskEntityExt = new PaymentTaskEntityExt();
                    BeanUtil.copyProperties(paasFormDataEntity, paymentTaskEntityExt);
                    updateLine = paymentTaskModel.update(paymentTaskEntityExt);
                    packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                    //paymentTaskService.afterSave(saasFormSaveDTO);
                    // 记录日志
                    opObjectName = paymentTaskEntityExt.getSerialNo();
                    newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(paymentTaskEntityExt));
//                    operateModuleTypeEnum = OperateModuleTypeEnum.PAYMENT_TASK_PUSH_SET;
                    operateModuleTypeEnum = OperateModuleTypeEnum.PaymentManage;
                    break;
                case DISTRIBUTOR_ACCOUNT:
                    oldPaasFormDataEntity.getData().remove(DistributorAccountEnum.DISTRIBUTOR_NAME_LINK_TEXT.getAttr());
                    packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                    distributorAccountService.afterSave(saasFormSaveDTO);
                    opObjectName = paasFormDataEntity.getData().getString(DistributorAccountEnum.NAME.getAttr());
                    newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(paasFormDataEntity));
                    operateModuleTypeEnum = OperateModuleTypeEnum.DISTRIBUTOR_ACCOUNT;
                    break;
                case CREDIT_LIMIT:
                    CreditLimitEntityExt creditLimitEntityExt = new CreditLimitEntityExt();
                    BeanUtil.copyProperties(paasFormDataEntity, creditLimitEntityExt);
                    updateLine = creditLimitModel.update(creditLimitEntityExt);
                    packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                    creditLimitService.afterSave(saasFormSaveDTO);
                    // 记录日志
                    opObjectName = serialNo;
                    newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(paasFormDataEntity));
                    operateModuleTypeEnum = OperateModuleTypeEnum.CREDIT_LIMIT;
                    break;
                case CREDIT_TEMPORARY_LIMIT:
                    // 申请人、申请时间不允许修改
                    data.put(CreditTemporaryLimitEnum.APPLY_ID.getAttr(), oldData.get(CreditTemporaryLimitEnum.APPLY_ID.getAttr()));
                    data.put(CreditTemporaryLimitEnum.APPLY_NAME.getAttr(), oldData.get(CreditTemporaryLimitEnum.APPLY_NAME.getAttr()));
                    data.put(CreditTemporaryLimitEnum.APPLY_TIME.getAttr(), oldData.get(CreditTemporaryLimitEnum.APPLY_TIME.getAttr()));
                    paasFormDataEntity.setData(data);
                    CreditTemporaryLimitEntityExt creditTemporaryLimitEntityExt = new CreditTemporaryLimitEntityExt();
                    BeanUtil.copyProperties(paasFormDataEntity, creditTemporaryLimitEntityExt);
                    updateLine = creditTemporaryLimitModel.update(creditTemporaryLimitEntityExt);
                    packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                    creditTemporaryLimitService.afterSave(saasFormSaveDTO);
                    // 记录日志
                    opObjectName = serialNo;
                    newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(paasFormDataEntity));
                    operateModuleTypeEnum = OperateModuleTypeEnum.CREDIT_TEMPORARY_LIMIT;
                    break;
                case CREDIT_FIXED_LIMIT:
                    // 申请人、申请时间不允许修改
                    data.put(CreditFixedLimitEnum.APPLY_ID.getAttr(), oldData.get(CreditFixedLimitEnum.APPLY_ID.getAttr()));
                    data.put(CreditFixedLimitEnum.APPLY_NAME.getAttr(), oldData.get(CreditFixedLimitEnum.APPLY_NAME.getAttr()));
                    data.put(CreditFixedLimitEnum.APPLY_TIME.getAttr(), oldData.get(CreditFixedLimitEnum.APPLY_TIME.getAttr()));
                    paasFormDataEntity.setData(data);
                    CreditFixedLimitEntityExt creditFixedLimitEntityExt = new CreditFixedLimitEntityExt();
                    BeanUtil.copyProperties(paasFormDataEntity, creditFixedLimitEntityExt);
                    updateLine = creditFixedLimitModel.update(creditFixedLimitEntityExt);
                    packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                    creditFixedLimitService.afterSave(saasFormSaveDTO);
                    // 记录日志
                    opObjectName = serialNo;
                    newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(paasFormDataEntity));
                    operateModuleTypeEnum = OperateModuleTypeEnum.CREDIT_FIXED_LIMIT;
                    break;
                default:
                    throw new XbbException(TemplateErrorCodeEnum.API_ERROR_350006);
            }

            //文件柜数据保存
            cabinetFileService.saveDataCabinetFile(formDataUpdateDTO.getExplainMap(), paasFormDataEntity, corpid, dataId, businessType, userId);
            afterSaveVO.setSuccess(updateLine);
            if(!isCoverage){
                String memoName = Objects.isNull(paasFormEntityExt) ? "" : paasFormEntityExt.getName();
                if(Objects.equals(redundantTemplateTypeEnum, RedundantTemplateTypeEnum.CUSTOMER)){
                    String isPublic = FastJsonHelper.getStringOrDefaultFromFormData(data, CustomerManagementEnum.IS_PUBLIC.getAttr(), "");
                    RedundantTemplateTypeEnum redundantTemplateTypeEnum4Log = RedundantTemplateTypeEnum.transferRedundantTemplateTypeEnum4Distributor(redundantTemplateTypeEnum, formDataUpdateDTO.getDistributorMark());
                    memoName = Objects.equals(isPublic, "1") ? PublicEnum.PUBLIC.getName() : redundantTemplateTypeEnum4Log.getName();
                }

                String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_WORK), userName, memoName, opObjectName);
                if(Objects.equals(redundantTemplateTypeEnum, RedundantTemplateTypeEnum.PAYMENT)){
                    // 负责人是获取当前登录人的ID，不准确,所属部门也没有模版字段，舍去
                    oldPaasFormDataEntity.setOwnerId(null);
                    oldPaasFormDataEntity.setDepartmentId(null);
                }
                JSONObject oldObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(oldPaasFormDataEntity));
                List<DetailLogPojo> detailArr = logHelp.getDetailArr4Data(corpid, redundantTemplateTypeEnum, formDataUpdateDTO.getExplainMap(), oldObj, newObj);
                mongoLogHelp.buildLog4DetailArr(detailArr, corpid, userId, userName, operateModuleTypeEnum, OperateTypeEnum.EDIT,
                        formDataUpdateDTO.getDataId().toString(), opObjectName, memo, formDataUpdateDTO.getHttpHeader());
            }
        } catch (XbbException e) {
            LOG.warn(BuinessDefaultErrorCodeEnum.API_ERROR_200019.getMsg(),e);
            // 老数据去除data内的无用无映射字段
            oldPaasFormDataEntity.getData().remove(FieldTypeEnum.UPDATETIME.getAlias());
            oldPaasFormDataEntity.getData().remove(FieldTypeEnum.CREATORID.getAlias());
            oldPaasFormDataEntity.getData().remove(FieldTypeEnum.ADDTIME.getAlias());
            oldPaasFormDataEntity.getData().remove(FieldTypeEnum.OWNERID.getAlias());
            oldPaasFormDataEntity.getData().remove(FieldTypeEnum.SERIALNO.getAlias());
            proEsHelper.reductionEsInUpdate(oldPaasFormDataEntity,oldPaasFormDataEntity.getId(),oldPaasFormDataEntity.getCorpid(), businessType,saasMark);
            String type = String.valueOf(businessType);
            Runnable runnable = () -> {
                try {
                    proEsHelper.otherRefEsDataRollBack(paasFormDataEntity,corpid,type,saasMark, reRollBackEntity);
                } catch (Exception e2) {
                    LOG.error("回滚其他表数据失败", e2);
                }
            };
            threadPoolBeanConfig.addUpdateDelThreadPool().execute(runnable);
            throw e;
        }catch (Exception e){
            LOG.error(BuinessDefaultErrorCodeEnum.API_ERROR_200019.getMsg(),e);
            // 老数据去除data内的无用无映射字段
            oldPaasFormDataEntity.getData().remove(FieldTypeEnum.UPDATETIME.getAlias());
            oldPaasFormDataEntity.getData().remove(FieldTypeEnum.CREATORID.getAlias());
            oldPaasFormDataEntity.getData().remove(FieldTypeEnum.ADDTIME.getAlias());
            oldPaasFormDataEntity.getData().remove(FieldTypeEnum.OWNERID.getAlias());
            oldPaasFormDataEntity.getData().remove(FieldTypeEnum.SERIALNO.getAlias());
            proEsHelper.reductionEsInUpdate(oldPaasFormDataEntity,oldPaasFormDataEntity.getId(),oldPaasFormDataEntity.getCorpid(), businessType,saasMark);
            String type = String.valueOf(businessType);
            Runnable runnable = () -> {
                try {
                    proEsHelper.otherRefEsDataRollBack(paasFormDataEntity,corpid,type,saasMark, reRollBackEntity);
                } catch (Exception e2) {
                    LOG.error("回滚其他表数据失败", e2);
                }
            };
            threadPoolBeanConfig.addUpdateDelThreadPool().execute(runnable);
            throw new XbbException(BuinessDefaultErrorCodeEnum.API_ERROR_200019);
        }
        return afterSaveVO;
    }



    @Override
    public PaasFormDataEntity getOldPaasFormDataEntity(FormDataUpdateDTO formDataUpdateDTO) throws XbbException {
        Integer saasMark = formDataUpdateDTO.getSaasMark();
        Long dataId = formDataUpdateDTO.getDataId();
        String corpid = formDataUpdateDTO.getCorpid();
        Integer businessType = formDataUpdateDTO.getBusinessType();
        PaasFormDataEntity oldPaasFormDataEntity = null;
        if (Objects.equals(saasMark, SaasMarkEnum.PAAS.getCode())) {
            oldPaasFormDataEntity = paasFormDataModel.getByKey(dataId, corpid);
        } else {
            PaasFormDataEntityExt paasFormDataEntityExt = saasUpdateHelp.getFormData(dataId, corpid, businessType);
            if (paasFormDataEntityExt != null) {
                oldPaasFormDataEntity = paasFormDataEntityExt;
            }
        }
        if (oldPaasFormDataEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
        }
        return oldPaasFormDataEntity;
    }

    @Override
    public PaasFormDataEntity getFormDataEntity(String corpid, Integer saasMark, Integer businessType, Long dataId) throws XbbException {
        PaasFormDataEntity paasFormDataEntity = null;
        if (Objects.equals(saasMark, SaasMarkEnum.PAAS.getCode())) {
            paasFormDataEntity = paasFormDataModel.getByKey(dataId, corpid);
        } else {
            PaasFormDataEntityExt paasFormDataEntityExt = saasUpdateHelp.getFormData(dataId, corpid, businessType);
            if (paasFormDataEntityExt != null) {
                paasFormDataEntity = paasFormDataEntityExt;
            }
        }
        if (paasFormDataEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
        }
        return paasFormDataEntity;
    }

    @Override
    public Long insertWorkOrder(FormDataAddDTO formDataAddDTO, WorkOrderEntity workOrderEntity) throws XbbException {
        Long dataId = 0L;
        Integer businessType = formDataAddDTO.getBusinessType();
        String corpid = formDataAddDTO.getCorpid();
        try {
            if (businessType == null || businessType == 0) {
                LOG.error("businessType为空");
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }
            // 工单data中移除负责人和协同人
            JSONObject conProductDataList = workOrderEntity.getData();
            conProductDataList.remove(FieldTypeEnum.OWNERID.getAlias());
            conProductDataList.remove(FieldTypeEnum.COUSERID.getAlias());
            conProductDataList.remove(FieldTypeEnum.SERIALNO.getAlias());
            JSONObject workOrderDataObj = (JSONObject) workOrderEntity.getData().clone();
            SaasFormSaveDTO saasFormSaveDTO = new SaasFormSaveDTO();
            BeanUtil.copyProperties(formDataAddDTO, saasFormSaveDTO);
            RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(businessType);
            // TODO: 2019/4/12 不知道干什么用,先留着  @author 魏荣杰  @date 2019/4/12 11:21
            SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo = formDataAddDTO.getSaasNeedRedundantAttrPoJo();
            if (redundantTemplateTypeEnum == RedundantTemplateTypeEnum.WORKORDER) {
                //关联的产品特殊处理
                JSONArray productArray = saasSaveHelp.formatSelectProduct4Save2(conProductDataList, WorkOrderEnum.SPARE_PARTS.getAttr());
                workOrderEntity.setData(conProductDataList);
                workOrderModel.insert(workOrderEntity);
                dataId = workOrderEntity.getId();
                saasFormSaveDTO.setIsNew(true);
                saasFormSaveDTO.setOldData(workOrderDataObj);
                saasFormSaveDTO.setNewData(workOrderDataObj);
                workOrderEntity.getData().put(WorkOrderEnum.SPARE_PARTS.getAttr(),productArray);
                saasFormSaveDTO.setOldWorkOrderEntity(workOrderEntity);
                saasFormSaveDTO.setNewWorkOrderEntity(workOrderEntity);
                saasFormSaveDTO.setSaasNeedRedundantAttrPoJo(saasNeedRedundantAttrPojo);
                workOrderService.afterSave(saasFormSaveDTO);

                //文件柜数据保存
                cabinetFileService.saveDataCabinetFile(formDataAddDTO.getExplainMap(), workOrderEntity, formDataAddDTO.getCorpid(), dataId, XbbRefTypeEnum.WORK_ORDER.getCode(), formDataAddDTO.getUserId());
            } else {
                throw new XbbException(TemplateErrorCodeEnum.API_ERROR_350006);
            }
        } catch (XbbException e) {
            LOG.warn(BuinessDefaultErrorCodeEnum.API_ERROR_200018.getMsg(),e);
            proEsHelper.physicalDeleteAllInAdd(dataId,corpid,businessType,SaasMarkEnum.SAAS.getCode());
            throw e;
        } catch (Exception e){
            LOG.error(BuinessDefaultErrorCodeEnum.API_ERROR_200018.getMsg(),e);
            proEsHelper.physicalDeleteAllInAdd(dataId,corpid,businessType,SaasMarkEnum.SAAS.getCode());
            throw new XbbException(BuinessDefaultErrorCodeEnum.API_ERROR_200018);
        }

        String serialNo = workOrderEntity.getSerialNo();
        String opName = RedundantTemplateTypeEnum.WORKORDER.getName();
        String userId = formDataAddDTO.getUserId();
        String creatorId = workOrderEntity.getCreatorId();
        String creatName = "";
        if(creatorId != null){
            // 走审批时获取创建人id
            UserEntity user = userModel.getByKeyIngoreDel(creatorId, corpid);
            creatName = Objects.isNull(user) ? "" : user.getName();
        }
        String userName = Objects.equals(workOrderEntity.getFlowStatus(), 2) ? creatName : formDataAddDTO.getLoginUserName();
        if (Objects.equals(userId, PaasConstant.OUT_LINK_USER_ID_PARAM) || Objects.equals(userId, PaasConstant.OUT_LINK_USER_ID)) {
            userName = PaasConstant.OUT_LINK_USER_NAME;
        }
        userId = Objects.equals(workOrderEntity.getFlowStatus(), 2) ? creatorId : userId;
        //记录日志
        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, opName, serialNo);
        mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.WORK, OperateTypeEnum.NEW,
                workOrderEntity.getId().toString(), serialNo, memo, formDataAddDTO.getHttpHeader());

        return dataId;
    }

    @Override
    public WorkOrderEntity getOldWorkOrderEntity(FormDataUpdateDTO formDataUpdateDTO) throws XbbException {
        String corpid = formDataUpdateDTO.getCorpid();
        Long dataId = formDataUpdateDTO.getDataId();
        WorkOrderEntity workOrderEntity = workOrderModel.getByKey(dataId, corpid);
        if (workOrderEntity == null || Objects.equals(workOrderEntity.getDel(), DelEnum.DELETE.getDel())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
        }
        return workOrderEntity;
    }

    @Override
    public void updateFormDataStatus(PaasProcessDataEntity paasProcessDataEntity, Integer flowStatus) throws XbbException {
        Integer saasMark = paasProcessDataEntity.getSaasMark();
        Integer businessType = paasProcessDataEntity.getBusinessType();
        Long formDataId = paasProcessDataEntity.getFormDataId();
        String corpid = paasProcessDataEntity.getCorpid();
        if (SaasMarkEnum.SAAS.getCode().equals(saasMark)) {
            RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(businessType);
            switch (redundantTemplateTypeEnum) {
                case CUSTOMER:
                    CustomerEntityExt customerEntity = new CustomerEntityExt();
                    customerEntity.setId(formDataId);
                    customerEntity.setCorpid(corpid);
                    customerEntity.setFlowStatus(flowStatus);
                    customerModel.update(customerEntity);
                    break;
                case SALES_OPPORTUNITY:
                    OpportunityEntityExt opportunityEntity = new OpportunityEntityExt();
                    opportunityEntity.setCorpid(corpid);
                    opportunityEntity.setId(formDataId);
                    opportunityEntity.setFlowStatus(flowStatus);
                    opportunityModel.update(opportunityEntity);
                    break;
                case CONTRACT:
                    ContractEntityExt contractEntity = new ContractEntityExt();
                    contractEntity.setCorpid(corpid);
                    contractEntity.setId(formDataId);
                    contractEntity.setFlowStatus(flowStatus);
                    contractModel.update(contractEntity);
                    List<ContractPerformanceEntity> updateDelList = new ArrayList<>();
                    if (Objects.equals(flowStatus, FlowStatusEnum.PASS.getType()) || Objects.equals(flowStatus, FlowStatusEnum.NOT_NEED_APPROVAL.getType())) {
                        contractPerformanceModel.setApprovalByContractId(formDataId, corpid, DelEnum.NORMAL.getDel(), updateDelList);
                    } else {
                        contractPerformanceModel.setApprovalByContractId(formDataId, corpid, DelEnum.APPROVE_STATUS.getDel(), updateDelList);
                    }
                    // todo 合同业绩分配操作日志
                    break;
                case REFUND:
                    RefundEntityExt refundEntity = new RefundEntityExt();
                    refundEntity.setCorpid(corpid);
                    refundEntity.setId(formDataId);
                    refundEntity.setFlowStatus(flowStatus);
                    refundModel.update(refundEntity);
                    break;
                case BOMBILL:
                    BomBillEntityExt bomBillEntity = new BomBillEntityExt();
                    bomBillEntity.setCorpid(corpid);
                    bomBillEntity.setId(formDataId);
                    bomBillEntity.setFlowStatus(flowStatus);
                    bomBillModel.update(bomBillEntity);
                    break;
                case PRODUCTIONORDER:
                    ProductionOrderEntityExt productionOrderEntity = new ProductionOrderEntityExt();
                    productionOrderEntity.setCorpid(corpid);
                    productionOrderEntity.setId(formDataId);
                    productionOrderEntity.setFlowStatus(flowStatus);
                    productionOrderModel.update(productionOrderEntity);
                    break;
                case INSTOCK:
                case PURCHASE_INSTOCK:
                case REFUND_INSTOCK:
                case OTHER_INSTOCK:
                case PRODUCTION_INSTOCK:
                case RETURNED_MATERIEL_INSTOCK:
                    InstockEntityExt instockEntity = new InstockEntityExt();
                    instockEntity.setCorpid(corpid);
                    instockEntity.setId(formDataId);
                    instockEntity.setFlowStatus(flowStatus);
                    instockModel.update(instockEntity);
                    break;
                case OUTSTOCK:
                case CONTRACT_OUTSTOCK:
                case OTHER_OUTSTOCK:
                case RETURNED_PURCHASE_OUTSTOCK:
                case WORK_ORDER_OUTSTOCK:
                case PRODUCTION_MATERIEL_OUTSTOCK:
                    OutstockEntityExt outstockEntity = new OutstockEntityExt();
                    outstockEntity.setCorpid(corpid);
                    outstockEntity.setId(formDataId);
                    outstockEntity.setFlowStatus(flowStatus);
                    outstockModel.update(outstockEntity);
                    break;
                case TRANSFER:
                    TransferEntityExt transferEntity = new TransferEntityExt();
                    transferEntity.setCorpid(corpid);
                    transferEntity.setId(formDataId);
                    transferEntity.setFlowStatus(flowStatus);
                    transferModel.update(transferEntity);
                    break;
                case INVENTORY:
                    InventoryEntityExt inventoryEntity = new InventoryEntityExt();
                    inventoryEntity.setCorpid(corpid);
                    inventoryEntity.setId(formDataId);
                    inventoryEntity.setFlowStatus(flowStatus);
                    inventoryModel.update(inventoryEntity);
                    break;
                case ASSEMBLE:
                    AssembleEntityExt assembleEntity = new AssembleEntityExt();
                    assembleEntity.setCorpid(corpid);
                    assembleEntity.setId(formDataId);
                    assembleEntity.setFlowStatus(flowStatus);
                    assembleModel.update(assembleEntity);
                    break;
                case PURCHASE:
                    PurchaseEntityExt purchaseEntity = new PurchaseEntityExt();
                    purchaseEntity.setCorpid(corpid);
                    purchaseEntity.setId(formDataId);
                    purchaseEntity.setFlowStatus(flowStatus);
                    purchaseModel.update(purchaseEntity);
                    break;
                case RETURNED_PURCHASE:
                    ReturnedPurchaseEntityExt returnedPurchaseEntity = new ReturnedPurchaseEntityExt();
                    returnedPurchaseEntity.setCorpid(corpid);
                    returnedPurchaseEntity.setId(formDataId);
                    returnedPurchaseEntity.setFlowStatus(flowStatus);
                    returnedPurchaseModel.update(returnedPurchaseEntity);
                    break;
                case INVOICE:
                    InvoiceEntityExt invoiceEntity = new InvoiceEntityExt();
                    invoiceEntity.setCorpid(corpid);
                    invoiceEntity.setId(formDataId);
                    invoiceEntity.setFlowStatus(flowStatus);
                    invoiceModel.update(invoiceEntity);
                    break;
                case PURCHASE_INVOICE:
                    PurchaseInvoiceEntityExt purchaseInvoiceEntityExt = new PurchaseInvoiceEntityExt();
                    purchaseInvoiceEntityExt.setCorpid(corpid);
                    purchaseInvoiceEntityExt.setId(formDataId);
                    purchaseInvoiceEntityExt.setFlowStatus(flowStatus);
                    purchaseInvoiceModel.update(purchaseInvoiceEntityExt);
                    break;
                case WORKORDER:
                    WorkOrderEntity workOrderEntity = new WorkOrderEntity(null);
                    workOrderEntity.setCorpid(corpid);
                    workOrderEntity.setId(formDataId);
                    workOrderEntity.setFlowStatus(flowStatus);
                    workOrderModel.update(workOrderEntity);
                    break;
                case PAYMENT_SHEET:
                    //需要读出回款单数据，判断其alone值，如果是父的，还需要联动更新子回款单审批状态
                    PaymentSheetEntityExt paymentSheetEntityExt = paymentSheetModel.getByKey(formDataId, corpid);
                    if (paymentSheetEntityExt == null) {
                        break;
                    } else if (Objects.equals(paymentSheetEntityExt.getAlone(), SheetAloneEnum.PARENT.getCode())) {
                        List<UpdateDataEntity> updateList = getUpdateDataList4Sheet(flowStatus, formDataId, corpid, IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET, paymentSheetEntityExt.getUuid());
                        paymentSheetModel.updateFlowStatusBatch(updateList, corpid);
                    } else {
                        paymentSheetEntityExt.setCorpid(corpid);
                        paymentSheetEntityExt.setId(formDataId);
                        paymentSheetEntityExt.setFlowStatus(flowStatus);
                        paymentSheetModel.update(paymentSheetEntityExt);
                    }
                    break;
                case PAY_SHEET:
                    //需要读出付款单数据，判断其alone值，如果是父的，还需要联动更新子付款单审批状态
                    PayPlanSheetEntityExt payPlanSheetEntityExt = payPlanSheetModel.getByKey(formDataId, corpid);
                    if (payPlanSheetEntityExt == null) {
                        break;
                    } else if (Objects.equals(payPlanSheetEntityExt.getAlone(), SheetAloneEnum.PARENT.getCode())) {
                        List<UpdateDataEntity> updateList = getUpdateDataList4Sheet(flowStatus, formDataId, corpid, IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET, payPlanSheetEntityExt.getUuid());
                        payPlanSheetModel.updateFlowStatusBatch(updateList, corpid);
                    } else {
                        payPlanSheetEntityExt.setCorpid(corpid);
                        payPlanSheetEntityExt.setId(formDataId);
                        payPlanSheetEntityExt.setFlowStatus(flowStatus);
                        payPlanSheetModel.update(payPlanSheetEntityExt);
                    }
                    break;
                case QUOTATION:
                    QuotationEntityExt quotationEntityExt = new QuotationEntityExt();
                    quotationEntityExt.setCorpid(corpid);
                    quotationEntityExt.setId(formDataId);
                    quotationEntityExt.setFlowStatus(flowStatus);
                    quotationModel.update(quotationEntityExt);
                    break;
                case SUPPLIER:
                    SupplierEntityExt supplierEntityExt = new SupplierEntityExt();
                    supplierEntityExt.setCorpid(corpid);
                    supplierEntityExt.setId(formDataId);
                    supplierEntityExt.setFlowStatus(flowStatus);
                    supplierModel.update(supplierEntityExt);
                    break;
                case SUPPLIER_CONTACT:
                    SupplierContactEntityExt supplierContactEntityExt = new SupplierContactEntityExt();
                    supplierContactEntityExt.setCorpid(corpid);
                    supplierContactEntityExt.setId(formDataId);
                    supplierContactEntityExt.setFlowStatus(flowStatus);
                    supplierContactModel.update(supplierContactEntityExt);
                    break;
                case CONTACT:
                    ContactEntityExt contactEntityExt = new ContactEntityExt();
                    contactEntityExt.setCorpid(corpid);
                    contactEntityExt.setId(formDataId);
                    contactEntityExt.setFlowStatus(flowStatus);
                    contactModel.update(contactEntityExt);
                    break;
                default:
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }
        } else {
            PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
            paasFormDataEntity.setCorpid(corpid);
            paasFormDataEntity.setId(formDataId);
            paasFormDataEntity.setFlowStatus(flowStatus);
            paasFormDataModel.update(paasFormDataEntity);
        }
    }

    /**
     * 把父单、子单都塞入要更新的updateList内：更新父单审批状态时，需要同步更新子单的审批状态
     * @param flowStatus 审批状态
     * @param formDataId 数据id
     * @param corpid 公司id
     * @param indexTypeEnum 回/付款单es索引
     * @param uuid 回/付款单uuid
     * @return java.util.List<com.xbongbong.pro.domain.entity.UpdateDataEntity>
     * @throws XbbException
     * @author zcp
     * @since v1.0
     * @version v1.0
     */
    private List<UpdateDataEntity> getUpdateDataList4Sheet(Integer flowStatus, Long formDataId, String corpid, IndexTypeEnum indexTypeEnum, String uuid) throws XbbException {
        List<UpdateDataEntity> updateList = new ArrayList<>();
        long now = DateUtil.getNow();
        //把数据本身置入要更新的list
        updateList.add(new UpdateDataEntity(formDataId, corpid, flowStatus, new ArrayList<>(), now));
        List<PaasFormDataEntityExt> childList = fundHelp.getChildEsDataListByParentUuid(indexTypeEnum, corpid, uuid, null);
        for (PaasFormDataEntityExt entityExt : childList) {
            UpdateDataEntity updateDataEntity = new UpdateDataEntity(entityExt.getId(), corpid, flowStatus, new ArrayList<>(), now);
            updateList.add(updateDataEntity);
        }
        return updateList;
    }

    @Override
    public void saveLinkPayment(SaasFormSaveDTO saasFormSaveDTO, PaasFormDataEntity paasFormDataEntity, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPoJo) throws XbbException {

    }

    @Override
    public void saveLinkPaymentSheet(SaasFormSaveDTO saasFormSaveDTO, PaasFormDataEntity paasFormDataEntity, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPoJo) throws XbbException {

    }
}
